Double on click event with mapbox gl

戏子无情 提交于 2019-12-22 18:11:48

问题


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:


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 
    });
  }
}


来源:https://stackoverflow.com/questions/45663869/double-on-click-event-with-mapbox-gl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!