Oskar Gusgård
Oskar Gusgård

Reputation: 477

Clicking on a marker clicks the layer below it (Mapbox-gl)

When I click a marker on the map, the click will also be registered by the onclick listener of the trail running below the marker. How could I stop this from happening? I want the click to only be registered by the marker's onclick listener.

Marker on map

Code for the marker:

var el = document.createElement('div');
    el.className = 'marker';
    el.addEventListener('click', () => {
        //functions
    })

    const marker = new mapboxgl.Marker(el)
      .setLngLat([location.longitude, location.latitude])
      .addTo(this.map);

Code for the layer:

map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
          "type": "geojson",
          "data": path
        },
        "layout": {
          "line-join": "round",
          "line-cap": "round"
        },
        "paint": {
          "line-color": "#888",
          "line-width": 8
        }
      });

Upvotes: 3

Views: 1313

Answers (1)

MeltedPenguin
MeltedPenguin

Reputation: 797

Try capturing the event and stopping its propagation:

el.addEventListener('click', e => {
    e.stopPropagation();
    //functions
}, true);

Upvotes: 2

Related Questions