Tuesday, 29 January 2019

geojson - Combining popup info from overlapping polygons in Mapbox GL JS


I've tried several solutions, but I'm having trouble populating a popup with information from overlapping polygons. When there are polygons that overlap, I want to drill down and pull the names from all polygons at the click point. Any help on this would be awesome.


 // When a click event occurs on a feature in the states layer, open a popup at the 
location of the click, with description HTML from its properties.



map.on('click', 'testlayer', function (e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(e.features[0].properties.name)
.addTo(map);
});

The jsfiddle here


enter image description here




Answer



Within your map.on('click') callback, e.features is an array of all features from testlayer at the point clicked.


So instead of only choosing the first in your popup, you can display all values like this:


map.on('click', 'testlayer', function (e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(e.features.map(function(feature) { return feature.properties.name; }).join(', '))
.addTo(map);
});


This extracts the name property from each feature and joins them into a string separated by ,.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...