一、说明
使用 L.Control 对象做扩展(API 地址)
二、控件
这里取名为 MyZoomLevel.js
// 图层级别
L.Control.MyZoomLevel = L.Control.extend({
options: {
position: 'bottomleft'
},
onAdd: function (map) {// L.Control原生方法
this._container = L.DomUtil.create('div', `gm-leaflet-control-zoomlevel`);
L.DomEvent.disableClickPropagation(this._container);
map.on('zoomend', this._onZoomEnd, this);
this._container.innerHTML = `${map.getZoom()} 级`;
return this._container;
},
onRemove: function (map) {// L.Control原生方法
debugger
// 删除DOM
L.DomUtil.remove(this._container);
// 删除监听
map.off('zoomend', this._onZoomEnd);
},
_onZoomEnd: function (e) {// 自定义方法
this._container.innerHTML = `${e.target.getZoom()} 级`;
}
});
L.Map.mergeOptions({
positionControl: false
});
L.Map.addInitHook(function () {
if (this.options.positionControl) {
this.positionControl = new L.Control.MyZoomLevel();
this.addControl(this.positionControl);
}
});
// 添加到L.control 控件中,注意这里是小写
L.control.myZoomLevel = function (options) {
return new L.Control.MyZoomLevel(options);
};
知识点:
1、 代码第 2、29、35 行,扩展控件使用 L.Control,注意首字母是大写。
2、代码第 34 行,添加到 L.control,注意首字母小写。
3、代码第 6 和13 行,onAdd 和 onRemove 是 L.Control 原生方法。代码第 20 行,_onZoomEnd 是自定义方法。监听地图缩放事件。
三、使用
let zoomLevel = L.control.myZoomLevel(
{
position: 'bottomleft'// 显示位置,有4个'topleft', 'topright(默认)', 'bottomleft' or 'bottomright'
}
).addTo(map)
四、移除
// 继承 L.Control remove 方法
zoomLevel.remove();