使用Mapbox gl双击事件 [英] Double on click event with mapbox gl

查看:1128
本文介绍了使用Mapbox gl双击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在style.load事件上重绘图层并删除图层

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

但是如何删除map.on('click')事件?当我单击该点时,Popup()将显示2次.当我再次更改图层时,onclick事件将触发3次,依此类推.所以我认为我必须删除click事件,但是如何删除?谢谢

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

推荐答案

您可能想使用map.once().这将为指定的事件类型添加仅被调用一次的侦听器.但是,在触发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

使用map.off()基本上与map.on()相反,您可以使用它取消注册任何已应用的事件侦听器.但是,您需要添加不带匿名函数的事件侦听器才能使用map.off().

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

这篇关于使用Mapbox gl双击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆