Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 778
Zarko Avatar asked Jul 16 '15 07:07

Zarko


People also ask

How do you add a marker to a Mapbox GL JS?

Style markers First, add the CSS you'll need to style your markers. In this case, add the image file you downloaded as the background-image for a class called marker . In your same index. html file, copy and paste the code inside your style tag below the #map declaration.

How do you change the color of a marker in Mapbox?

var marker = new mapboxgl. Marker({ "color": "#b40219" }) . setLngLat([0, 0]) . addTo(map);

How do I style a marker in Mapbox?

To style a marker, you can add simplestyle to your GeoJSON, load a custom image, or create your own markers with HTML and CSS.

How do I get coordinates from Mapbox?

If you need to find a location's latitude and longitude, you can use the Mapbox Search playground, which allows you to search for a location and retrieve its coordinates in longitude,latitude format.


1 Answers

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");         });       }); 
like image 179
beginner's_luck Avatar answered Oct 13 '22 23:10

beginner's_luck