I am redrawing layers on style.load event and removing the layers
map.on('style.load', function() {
loadByBounds(tempBounds)
});
function loadByBounds(b) {
if (map.getLayer("cluster-count")) {
map.removeLayer("cluster-count");
}
...
map.on('click', 'unclustered-point', function(e) {
var popup = new mapboxgl.Popup()
.setLngLat(e.features[0].geometry.coordinates)
.setHTML(text)
.addTo(map);
})}
But how to remove map.on('click') events? As when I click the point the Popup() displays 2 times. And when I change layer one more time the onclick event fires 3 times and so on. So I think I have to remove the click event but how? Thanks
You might wanna use
map.once()
. This will add a listener that will be called only once to a specified event type. However after 1 click event got fired this event listener won't listen to any further click events.https://www.mapbox.com/mapbox-gl-js/api/#evented#once
With
map.off()
it's basically the opposite ofmap.on()
and you can use it to unregister any applied event listeners. However you would need to add event listeners without an anonymous function in order to usemap.off()
.https://www.mapbox.com/mapbox-gl-js/api/#map#off
To prevent your app from registering multiple listeners you maybe need to set a flag that gets set after your first event listener got applied.