Reputation: 37
I have it so that clicking on the map creates a marker at that point. I am trying to add an event to the markers that will return the lnglat when the marker is clicked. The issue is I can't click the marker, the map just keeps creating new markers.
map.on('click', function(e){
let marker = new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map);
marker.on('click', function(){
console.log('hello');
});
});
Upvotes: 3
Views: 4593
Reputation: 797
Markers are simple HTML elements, so you can add an event listener directly to them by calling addEventListener
on their DOM node:
map.on('click', function(e){
var el = document.createElement('div');
el.className = 'marker';
el.style.height = '20px';
el.style.width = '20px';
el.style.backgroundColor = 'black';
el.addEventListener('click', function(e){
// Prevent the `map.on('click')` from being triggered
e.stopPropagation();
console.log('hello');
});
let marker = new mapboxgl.Marker(el).setLngLat(e.lngLat).addTo(map);
});
https://codepen.io/eddydg/pen/gZpbRj?editors=1010
Upvotes: 3