mapbox 添加自定义控件

553 阅读1分钟

最近学习mapbox中,需要添加自定义控件。自定义控件需要实现一定的接口(具有特定的方法函数)。一旦具备了这些方法,就可以使用 addControl 方法将自定义控件添加到地图上。

class MyCustomControl{
  // 定义一个 container 作为控件的主体
  container = document.createElement('div');

  onAdd(map) {
    this.container.style.width = '100px';
    this.container.style.height = '50px';
    this.container.style.backgroundColor = '#fff';
    this.container.style.border = '2px solid #000';
    this.container.innerText = 'My Custom Control';
    return this.container;
  }

  onRemove() {
    this.container.parentNode.removeChild(this.container);
    this.map = undefined;
  }
}

自己需要实现onAdd() 方法和onRemove()方法

// 初始化地图
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [longitude, latitude],
    zoom: 9
});

map.on('load', function () {
    var myCustomControl = new MyCustomControl();
    map.addControl(myCustomControl, 'top-right');  // 添加自定义控件到地图的右上角
});

在页面中就可以显示自定义控件

image.png

遇到的问题 代码添加上去之后,页面中并没有显示,这是可能因为没有添加mapbox样式文件。需要导入mapbox-gl.css样式文件。我是网上下载下来对应文件之后静态引入的。

image.png