Mapbox GL JS: ignore map click event if marker is clicked

与世无争的帅哥 提交于 2019-12-04 07:40:30

I think what you wanna do is to stop the event from getting handled twice when the user clicked on a marker. To do that you could just use event.stopPropagation();

See: https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation

In your code you can use it like this:

 function handleKitten(e) {
   e.target.style.backgroundImage = 'url(http://placekitten.com/g/50/50)';
   e.stopPropagation();
 }

 function handleMapClick(e) {
   console.log('handleMapClick', e);
 }

 var map = new mapboxgl.Map({
   container: 'map',
   style: 'mapbox://styles/mapbox/streets-v9',
   center: [-65.017, -16.457],
   zoom: 5
 });

 var el = document.createElement('div');
 el.style.backgroundImage = 'url(https://placekitten.com/g/40/40/)';
 el.style.width = 40 + 'px';
 el.style.height = 40 + 'px';

 new mapboxgl.Marker(el)
   .setLngLat([ -63.29223632812499, -18.28151823530889 ])
   .addTo(map);

 el.addEventListener('click', handleKitten, false);
 map.on('click', handleMapClick);

I made a quick jsfiddle for demonstration: https://jsfiddle.net/andi_lo/guzskv7n/7/

You might wanna use map.once(), or map.off(), see: Double on click event with mapbox gl

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