3
votes

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

1

1 Answers

5
votes

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 of map.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 use map.off().

https://www.mapbox.com/mapbox-gl-js/api/#map#off

// you would need to use a named function
  function clickHandler(e) {
    // handle click
  }

  map.on('click', clickHandler);
// then you can use 
  map.off('click', clickHandler);
  
// With an anonymous function you won't be able to use map.off
  map.on('click', (e) => {
    // handle click
  });

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.

let notListening = true;

function loadByBounds(b) {
  // ....
  if (notListening) {
    notListening = false;
    map.on('click', (e) => { 
      // do something 
    });
  }
}