gpt4 book ai didi

javascript - 如何在 Mapbox GL JS 中添加自定义地理定位我按钮?

转载 作者:行者123 更新时间:2023-12-03 07:08:05 28 4
gpt4 key购买 nike

我正在尝试向我的 map 添加一个自定义的 Geolocate me 按钮,它有点工作,但前提是我还添加了 Mapbox 中的标准图标。下面的代码有效,但如果我删除行 map.addControl(geolocate, 'top-right'); ,我的左键停止工作。

      // Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate, 'top-right');

class ToggleControl {

constructor(options) {
this._options = Object.assign({}, this._options, options)
}

onAdd(map, cs) {
this.map = map;
this.container = document.createElement('div');
this.container.className = `${this._options.className}`;

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 = 'Use my location';
el.addEventListener('click', (e) => {
geolocate.trigger();
}, false)
return el;
}
}
const toggleControl = new ToggleControl({
className: 'mapboxgl-ctrl'
})
map.addControl(toggleControl, 'top-left')
screenshot - 蓝色是我要保留的,红色是要删除的

最佳答案

您可以扩展 mapboxgl.GeolocateControl 类,而不是创建新的 mapboxgl.GeolocateControl 实例,如下所示:

class ToggleControl extends mapboxgl.GeolocateControl {
_onSuccess(position) {
this.map.flyTo({
center: [position.coords.longitude, position.coords.latitude],
zoom: 17,
bearing: 0,
pitch: 0
});
}

onAdd(map, cs) {
this.map = map;
this.container = document.createElement('div');
this.container.className = `mapboxgl-ctrl`;
const button = this._createButton('monitor_button')
this.container.appendChild(button);
return this.container;
}

_createButton(className) {
const el = window.document.createElement('button')
el.className = className;
el.textContent = 'Use my location';
el.addEventListener('click', () => {
this.trigger();
});
this._setup = true;
return el;
}
}
const toggleControl = new ToggleControl({})
map.addControl(toggleControl, 'top-left')
其他有用的链接:
  • Mapbox gl Class URL: 看看https://github.com/mapbox/mapbox-gl-js/blob/520a4ca3b9d260693f1e7f4af30d8b91c8f8bb08/src/ui/control/geolocate_control.js#L97-L565
  • How to wrap a ui control (mapbox geolocation control)
  • 关于javascript - 如何在 Mapbox GL JS 中添加自定义地理定位我按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709340/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com