如何在Mapbox GL JS中添加自定义geolocate me按钮?

问题描述

我试图在地图上添加一个自定义的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')

其他有用的链接: