2
votes

For a current project i'm using mapbox to show area's and show markers on top of those area's. Both should have a popup with a short description.

The marker is HTML + CSS and has a pop attached to it, according to the documentation here: https://www.mapbox.com/help/custom-markers-gl-js/

new mapboxgl.Marker(el)
   .setLngLat(marker.geometry.coordinates)
   .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
   .setHTML('<h3>' + marker.properties.title + '</h3><p>' + 
      marker.properties.description + '</p>'))
   .addTo(map);

The area's are drawn by adding a layer with geojson object as described in this example: https://122e4e-mapbox.global.ssl.fastly.net/mapbox-gl-js/example/polygon-popup-on-click/. Listening to the click events like this:

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

This all works fine, until a marker is positioned on top of another layer. When clicking the marker both the popup of the marker and the popup of the layer/polygon show.

Expected Result: To only show the popup of the marker since this is the top element clicked.

There is no on('click') for markers.

2

2 Answers

2
votes

In the end i've used the following workaround:

Create marker with custom HTML and give it a class.

Now when listening to the click event for the area popup, check if the target classList contains the marker class en return and let mapbox internally handle the marker popup.

map.on('click', 'states-layer', function (e) { if (event.originalEvent.target.classList.contains(MARKER_CLASS)) return; }

Hope this helps if anybody encounters the same issue.

0
votes

If you're using new mapboxgl.Popup() each time the map is clicked, then yes, you'll get a, well, "new MapboxGL popup" :)

You need to reuse your existing popup, like this:

var popup = new mapboxgl.Popup();
map.on('click', 'states-layer', function (e) {
    popup.setLngLat(e.lngLat)
        .setHTML(e.features[0].properties.name)
        .addTo(map);
});