《Leaflet 基础知识点》- 自定义控件 - 图层级别

一、说明

使用 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();

五、效果

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值