Using the mapboxgl, I added a my custom map control, which can do some special functions,and I refered the office example with basic function. But When I completed codes, I found the event click of button did not work. I have add the stopPropagation function. So how to add click event in the mapbox control?
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>
The problem is that the mapbox container positioning style removes mouse events handling (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;
}
So you need to add the class mapboxgl-ctrl
(pointer-events: auto;
) to the container for catching events:
this.container.className = 'mapboxgl-ctrl my-custom-control';
Or set this CSS-property manually:
.my-custom-control {
pointer-events: auto;
}
[ https://jsfiddle.net/Lkes0ch8/ ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With