使用mapboxgl,我添加了一个自定义地图控件,该控件可以执行某些特殊功能,并引用了具有基本功能的Office示例。但是,当我完成代码后,我发现按钮的事件单击不起作用。我添加了stopPropagation函数。那么如何在mapbox控件中添加click事件呢?
mapboxgl.accessToken = 'pk.eyJ1IjoieGlhb2thbmciLCJhIjoiY2lqc2d2NXlyMGhkbHU0bTVtcGNiOWxseCJ9.J5qsX13KKNT1slMGS-MOLg';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', // stylesheet location
center: [-74.50, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});
class ToggleControl {
onAdd(map){
this.map = map;
this.container = document.createElement('div');
this.container.className = 'my-custom-control';
const button = this._createButton('monitor_button')
this.container.appendChild(button);
return this.container;
}
onRemove(){
this.container.parentNode.removeChild(this.container);
this.map = undefined;
}
_createButton(className) {
const el = window.document.createElement('button')
el.className = className;
el.textContent = 'toggleControl';
el.addEventListener('click',(e)=>{
e.style.display = 'none'
console.log(e);
// e.preventDefault()
e.stopPropagation()
},false )
return el;
}
}
const toggleControl = new ToggleControl()
map.addControl(toggleControl,'top-left')
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Display a map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
</script>
</body>
</html>
答案 0 :(得分:3)
问题在于mapbox容器的定位样式删除了鼠标事件处理(pointer-events: none;
):
.mapboxgl-ctrl-top-left,
.mapboxgl-ctrl-top-right,
.mapboxgl-ctrl-bottom-left,
.mapboxgl-ctrl-bottom-right {
position: absolute;
pointer-events: none;
z-index: 2;
}
因此,您需要将类mapboxgl-ctrl
(pointer-events: auto;
)添加到容器中以捕获事件:
this.container.className = 'mapboxgl-ctrl my-custom-control';
或手动设置此CSS属性:
.my-custom-control {
pointer-events: auto;
}