Google Maps Api: cannot click on clickable polygon behind datalayer - javascript

Hi I am using google maps api(JavaScript) to build an interactive world map. It went really well until I ran into this problem. I am using polygons to show to outline of a country. These polygons trigger a modal showing information about the country when clicked on. This worked until I started to use "Data Layer: Earthquake data". Instead of using earthquake data I use sales information of the company I work at. So if a large share of our customers are from the Netherlands then the datalayer assigned to the Netherlands will be very large. The problem is that because of the datalayers the countries are no longer clickable. I can not click "through" the datalayer. Is there a possibility that I can trigger the event behind the datalayer?
This code displays the datalayers:
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
}
})
});
map.data.addListener('mouseover', function(event) {
map.data.overrideStyle(event.feature, {
title: 'Hello, World!'
});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
This code displays the polygons:
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0]
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
If read in the documentation that changing the zIndex won't work because "Markers are always displayed in front of line-strings and polygons."
Is there a way to click on a polygon behind a datalayer?
EDIT
I tried to give the polygon a higher zIndex and I made the datalayer not clickable
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickAble: false,
zIndex: 50
}
})
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0],
zIndex: 100
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
//console.log(map);
//test(map)
}
EDIT
Apparently the datalayer wasn't the problem, but the icon was. That is why it didn't work when I did this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickable: false
}
})
});
The correct way to do it is this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
},
clickable: false
})
});

You basically have 2 options here:
Set the zIndex of your Polygons to a higher number than the data layer. Your Polygons will be clickable but obviously will appear above the data layer, which might not be what you want.
Set the clickable property of the data layer to false so that you can click elements that are below. This will work if you don't need to react to clicks on the data layer...
Option 2 example code:
map.data.setStyle({
clickable: false
});
Edit: Full working example below, using option 2. As you can see the Polygon is below the data layer but you can still click it.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -28,
lng: 137
}
});
var polygon = new google.maps.Polygon({
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#00FF00',
fillOpacity: .6,
paths: [
new google.maps.LatLng(-26, 139),
new google.maps.LatLng(-23, 130),
new google.maps.LatLng(-35, 130),
new google.maps.LatLng(-26, 139)
],
map: map
});
polygon.addListener('click', function() {
console.log('clicked on polygon');
});
// Load GeoJSON
map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
// Set style
map.data.setStyle({
fillColor: '#fff',
fillOpacity: 1,
clickable: false
});
}
#map {
height: 200px;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map"></div>

I have found that after, setting the z-order, the maps api does not reliably send clicks to polygon feature in the top layer when there are many polygons.
I had one data layer of regions where each feature is a precinct boundary. When you click on one feature, it loads another data layer on top. The top layer consists of polygons inside the region with a higher z-order, representing house title boundaries within that region.
After the houses are loaded, clicking on a house should send the click to the house polygon, not the region. But this sometimes failed - especially if there are many houses.
To resolve the issue, after clicking on a region feature, I set that feature to be non clickable. Then the clicks always propagate to the correct house feature. You can still click on other features of the lower layer, just not the selected one. This solution should work if your data and presentation follows a similar pattern.
/* private utility is only called by this.hideOnlyMatchingFeaturesFromLayer() */
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle) {
if (feature.getProperty(key) === value) {
if (this.map) {
layer.overrideStyle(feature, overrideStyle);
}
} else {
if (this.map) {
layer.overrideStyle(feature, defaultStyle);
}
}
}
/* Apply an overrideStyle style to features in a data layer that match key==value
* All non-matching features will have the default style applied.
* Otherwise all features except the matching feature is hidden!
* Examples:
* overrideStyle = { clickable: false,strokeWeight: 3}
* defaultStyle = { clickable: true,strokeWeight: 1}
*/
overrideStyleOnMatchingFeaturesInLayer(layer, key, value, overrideStyle, defaultStyle) {
layer.forEach((feature) => {
if (Array.isArray(feature)) {
feature.forEach((f) => {
_overrideStyleOnFeature(f, layer, key, value, overrideStyle, defaultStyle);
});
} else {
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle);
}
});
}
/* example usage */
overrideStyleOnMatchingFeaturesInLayer(
theRegionsDataLayer,
'PROP_NAME',
propValue,
{ clickable: false, strokeWeight: 3},
{ clickable: true, strokeWeight: 1}
);

Related

Creating Radar Map on Google Maps JavaScript API

I have a response data from a Radar Layer API like this:
{
"Date": "2020-04-18T04:00:05+03:00",
"Source": 2,
"Kml": [
{
"Polygons": [
{
"Polygon": [
{ "Cordinates": [25.8409, 51.6199] },
{ "Cordinates": [25.8341541, 51.619873] },
{ "Cordinates": [25.834177, 51.61238] },
{ "Cordinates": [25.8308582, 51.5936356] },
{ "Cordinates": [25.8275185, 51.5823822] }
....
....
]
}
],
"Color": "#47C247"
},
{
"Polygons": [
{
"Polygon": [
{ "Cordinates": [26.1740189, 50.5239372] },
{ "Cordinates": [26.1841354, 50.5238838] },
{ "Cordinates": [26.1909122, 50.53136] },
{ "Cordinates": [26.1977215, 50.5463562] }
....
....
]
}
],
"Color": "#47C247"
},
...
...
I want to create a Radar map using this data.
I tried to create polygons using each data and created a set interval function to loop through each polygon for 250ms so that it acts as an animation.
setInterval(() => {
deleteAllShape();
// console.log(data);
data.Kml.map((polygons) => {
const shape = polygons.Polygons.map((polygon) => {
const newMapData = [];
polygon.Polygon.map((obj) => {
const path = { lat: obj.Cordinates[0], lng:
obj.Cordinates[1] };
newMapData.push(path);
});
poly = new google.maps.Polygon({
paths: newMapData,
strokeColor: polygons.Color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: polygons.Color,
fillOpacity: 0.35,
draggable: false,
editable: false,
});
poly.setMap(map);
allPolygons.push(poly);
});
});
},250)
function deleteAllShape() {
poly = null;
for (let i = 0; i < allPolygons.length; i++) {
allPolygons[i].setMap(null);
}
}
This is working to an extend. But the problem is the map and the browser slows down and hangs up after creating some polygons.
When I researched on several radar maps (eg: windy.com) :-
I found that they are rendering images on the map. My question is how to create images using above data and create a radar map?
This may not answer your question, as I'm unclear what you're trying to do with images instead of polygons. However, it might speed things up.
Currently you loop over allPolygons every 250ms, preventing all previous polygons from appearing on the map.
Then you draw a new polygon, and add it into allPolygons, so it gets removed on the next iteration in 250ms. That's all fine.
However, as the number of polygons increase, you'll be increasing the size of that for loop each time:
for (let i = 0; i < allPolygons.length; i++) {
So it'll get progressively slower as you draw more polygons. You don't say how many polygons you're adding, but I'd guess it's a lot.
Instead, all you need to do is hide the most recently created polygon. All the previous ones in allPolygons will already have been hidden, so you don't need to call setMap(null) on every polygon, as it's just the most recent one that's not already set to null.
Maybe something like:
function deleteAllShape() {
allPolygons[allPolygons.length - 1].setMap(null);
}
Alternatively, just this, if you don't need allPolygons for anything else, save you having to store them in that array.
poly.setMap(null);
Also, instead of creating poly then calling poly.setMap(map);, just do
poly = new google.maps.Polygon({
paths: newMapData,
strokeColor: polygons.Color,
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: polygons.Color,
fillOpacity: 0.35,
draggable: false,
editable: false,
map
});

How to handle the click event on all the polylines when the cursor is on overlapped polylines?

I have many polylines on map and, if the user click some, I want to "select" the intended polyline, but sometimes polylines can get overlapped. So, if the user wants to select one and click on 2, I want to know what the polylines were clicked by the user and display it. How can I do that?
I tried to write some code that loops the polylines and checks if the clicked location is on some drawing, but does not work because click on drawings does not mean click on the polyline geolocation.
Here's my code: (Run in JSFiddle)
// this example creates 2 polylines (one red, one blue) and add event listener
// to "click", and the handler loops over "polylines" (an array with the 2
// polylines created)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: -25,
lng: -50
},
mapTypeId: 'terrain'
});
var isOnPolyline = function (point, polyline) {
if (point instanceof google.maps.Marker) {
point = point.getPosition();
}
return google.maps.geometry.poly.isLocationOnEdge(point, polyline, 0.0001) ||
google.maps.geometry.poly.containsLocation(point, polyline);
};
var red = new google.maps.Polyline({
path: [{
lat: -25.006,
lng: -52
},
{
lat: -25.006,
lng: -51
}
],
map: map,
name: "red",
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 10
});
red.addListener("click", function (e) {
polylines.map(function (p) {
if (isOnPolyline(e.latLng, p)) {
console.log("hey, you clicked the " + p.name + " one");
}
});
});
var blue = new google.maps.Polyline({
path: [{
lat: -25,
lng: -53
},
{
lat: -25,
lng: -50
}
],
name: "blue",
map: map,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 6
});
blue.addListener("click", function (e) {
polylines.map(function (p) {
if (isOnPolyline(e.latLng, p)) {
console.log("hey, you clicked the " + p.name + " one");
}
});
});
var polylines = [red, blue];
}
so I tried to click as shown in the figure (cursor is the yellow circle):
I expected the console logs:
"hey, you clicked the red one
hey, you clicked the blue one"
But nothing was logged.

How to remove drawn circle or polygon from google map using drawing manager - ng2-map

How can I remove the drawn circle or polygon using drawing manager from the google map.
Component:
import {Ng2MapComponent, DrawingManager, Polygon} from 'ng2-map';
export class CreateAlertComponent implements OnInit {
#ViewChild(Ng2MapComponent) mapObj: Ng2MapComponent;
#ViewChild(DrawingManager) drawingManager: DrawingManager;
polygonCompleteFunction(e) {
console.log(this.mapObj);
};
});
HTML:
<ng2-map [zoom]="mapOptions.zoom" [minZoom]="mapOptions.minZoom" [center]="mapOptions.center" clickable="false" (click)="mapClick($event)">
<drawing-manager *ngIf = "selectedJurisdictions.length > 0"
[drawingMode]="'null'"
[drawingControl]="true"
[drawingControlOptions]="{
position: 2,
drawingModes: ['circle', 'polygon']
}"
[circleOptions]="{
fillColor: 'red',
fillOpacity: 0.3,
strokeColor: 'black',
strokeWeight: 2,
editable: true,
draggable: true,
zIndex: 1
}"
[polygonOptions]="{
fillColor: 'red',
fillOpacity: 0.3,
strokeColor: 'black',
strokeWeight: 2,
editable: true,
draggable: true,
zIndex: 1
}"
(polygoncomplete)="polygonCompleteFunction($event)"
(circlecomplete)="circleCompleteFunction($event)">
</drawing-manager>
</ng2-map>
But on polygon complete function or circle complete I am not getting the drawn polygons from the map object
You can find the drawn Polygon or Circle from the CircleComplete/PolygonCompolete Event's parameter. Or find the target from OverlayComplete event's parameter by event.overlay.
After get the target object, you can keep it somewhere for deleteing them somewhere else.
polygonCompleteFunction(e) {
console.log(e); // this is the drawn Polygon you are looking for, and same for the circleComplete event
};
overlayComplete(e) {
console.log(e.overlay); // here can also find the drawn shape(Polygon/Circle/Polyline/Rectangle)
}
While deleting the target Polygon or Circle, delete them by reference the instance kept before.
target.setMap(null);
Here is the GooleMapApi Documentation about OverlayComplete Events:
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle)
{
var radius = circle.getRadius();
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event)
{
if (event.type == 'circle') {
var radius = event.overlay.getRadius();
}
});
Here is the link to GoogleMapApi documentation.
Hope it helps. And here is a plunker you can take reference.

building multiple polygons by function in google maps javascript

I want to build a lot of areas in google maps, and have each defined with a polygon.
If I do it one by one it works without a problem (inside the initialize func):
name = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//some event
//highlights polygon when mouseover
google.maps.event.addListener(name, 'mouseover', function () {
name.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
//then displaying it on the map:
name.setMap(map);
Now I want to have a function to just put in the coords to build the polygons, something like this. But just calling the function stops other polygons from being rendered, so I know there is a problem calling it:
iName = new drawPolygon(polyName, coords);
iName.setMap(map);
The function looks like this:
function drawPolygon(polyName, coords) {
polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
//fillColor: 'green',
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
}
any help as to why, how am I calling it wrong?
drawPolygon doesn't have a return statement. It returns null. nulldoesn't have a .setMap method.
Expanding on geocodezip's answer, just add a return statement to your function.
function drawPolygon(polyName, coords) {
polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
return polyName;
}
I'd also be inclined to in that case not bother passing polyName into the function as an argument. You don't bother showing us the code where you create the polyName variable prior to calling drawPolygon. But I assume you're not doing anything particularly clever with it that would require you to do so.
So refactored:
iName = new drawPolygon(coords);
iName.setMap(map);
function drawPolygon(coords) {
var polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
return polyName;
}

google maps draw a line between two points

I am getting the latitude/longitude from the DB. I am unable to draw a line between two distances. Here is my code
var auto_refresh = setInterval(
function () {
$.get('http://developer.allsecure.me/Location/longlat', function (data) {
map_canvas.setCenter(new google.maps.LatLng(data.startlat, data.startlong));
clearMarkers();
setMarker(map_canvas, 'center', new google.maps.LatLng(data.startlat, data.startlong), '', '/img/device.png', '', '', true);
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(data.startlat, data.startlong), new google.maps.LatLng(data.endlat, data.endlong)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
map: map
});
}, 'json');
}, 1000);
I don't know why it isn't adding the polylines between the two distances.
As the comment above was the actual solution
When you define the line you use map: map shouldn't this be map: map_canvas?

Categories

Resources