css 如何在Mapboxgl中创建带有事件的自定义控件?

ergxz8rk  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(227)

使用mapboxgl,我添加了一个我的自定义Map控件,它可以做一些特殊的功能,我参考了办公室的例子与基本功能。但当我完成代码,我发现事件点击按钮不工作。我已经添加了stopPropagation函数。那么如何添加点击事件在mapbox控件?

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>
fquxozlt

fquxozlt1#

问题在于Map框容器定位样式删除了鼠标事件处理(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-ctrlpointer-events: auto;)添加到容器中以捕获事件:

this.container.className = 'mapboxgl-ctrl my-custom-control';

或者手动设置此CSS属性:

.my-custom-control {
    pointer-events: auto;
}

[ https://jsfiddle.net/Lkes0ch8/ ]

hgb9j2n6

hgb9j2n62#

我有同样的问题,stdob--是正确的,通过添加'mapboxgl-ctrl'到className解决了我的问题。没有这个,用户不能拖动滑动条。

this._container.className = 'mapboxgl-ctrl  mapboxgl-ctrl-group opacityDIV';

右上角的滑块是我创建的。x1c 0d1x
有两种方法添加mapbox控件,
标准方式来自MapBox示例,
另一种方法是相同的
下面是我的工作代码:

相关问题