How to add "click" listener on marker in mapbox-gl-js

Zarko picture Zarko · Jul 16, 2015 · Viewed 26.1k times · Source

I added few markers on the map using folowing this example:

https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/

Now I want to show popup when user clicks on marker image, but i can not find elegant solution. Any help?

Answer

beginner's_luck picture beginner's_luck · Nov 23, 2019

I also had the same problem but I found a workaround without having to create an html element.

I Used getElement() function that return Marker like a HTML Element and after i attach the click event.

      this.service.getAllData().forEach(e => {
        // create MapBox Marker
        const marker = new mapboxgl.Marker().setLngLat([e.lon, e.lat]).addTo(this.map);
        // use GetElement to get HTML Element from marker and add event
        marker.getElement().addEventListener('click', () => {
          alert("Clicked");
        });
      });