《Leaflet 基础知识点》- 自定义控件 - 鼠标坐标信息

一、说明

使用 L.Control 对象做扩展(API 地址

 

二、控件

这里取名为 MyMousePosition.js

// 鼠标坐标位置信息
L.Control.MyMousePosition = L.Control.extend({
    options: {
        position: 'bottomleft',
        emptyString: '经度: 0  纬度: 0',//默认信息
        lngFirst: true,
        numDigits: 4,//小数点位数
        lngFormatter: undefined,
        latFormatter: undefined,
        prefix: ""
    },
    onAdd: function (map) {// L.Control原生方法
        this._container = L.DomUtil.create('div', `gm-leaflet-control-mouseposition`);
        L.DomEvent.disableClickPropagation(this._container);
        map.on('mousemove', this._onMouseMove, this);
        this._container.innerHTML = this.options.emptyString;
        return this._container;
    },
    onRemove: function (map) {// L.Control 原生方法
        // 删除DOM
        L.DomUtil.remove(this._container);
        // 删除监听
        map.off('mousemove', this._onMouseMove)
    },
    _onMouseMove: function (e) {// 自定义方法
        var lng = this.options.lngFormatter ? this.options.lngFormatter(e.latlng.lng) : L.Util.formatNum(e.latlng.lng, this.options.numDigits);
        var lat = this.options.latFormatter ? this.options.latFormatter(e.latlng.lat) : L.Util.formatNum(e.latlng.lat, this.options.numDigits);
        var value = '经度:' + lng + '  纬度2:' + lat;
        var prefixAndValue = this.options.prefix + ' ' + value;
        this._container.innerHTML = prefixAndValue;
    }
});
L.Map.mergeOptions({
    positionControl: false
});
L.Map.addInitHook(function () {
    if (this.options.positionControl) {
        this.positionControl = new L.Control.MyMousePosition();
        this.addControl(this.positionControl);
    }
});
// 添加到L.control 控件中,注意这里是小写
L.control.myMousePosition = function (options) {
    return new L.Control.MyMousePosition(options);
};

 知识点:

1、 代码第 2、38、44 行,扩展控件使用 L.Control,注意首字母是大写。

2、代码第 43 行,添加到 L.control,注意首字母小写。

3、代码第 12 和19 行,onAdd 和 onRemove 是 L.Control 原生方法。代码第 25 行,_onMouseMove是自定义方法。监听鼠标移动事件。

三、使用

mousePosition = L.control.myMousePosition(
    {
        position: 'bottomleft'// 显示位置,有4个'topleft', 'topright(默认)', 'bottomleft' or 'bottomright'
    }
).addTo(map);

四、移除

// 继承 L.Control remove 方法
mousePosition.remove();

五、效果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值