【Leafletjs】5.L.Control 自定义一个Control

本文介绍了如何在Leafletjs中创建自定义的Control,包括使用构造器、配置选项、方法以及不同位置的控制。通过示例展示了创建一个图例控件的过程,包括基本模板和更复杂的扁平样式设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

L.Control

所有leaflet控制的基础类。继承自IControl接口。 你可以这样添加控件:

control.addTo(map);
// the same as
map.addControl(control);

构造器

构造器使用描述
L.Control( <Control optionsoptions? ) new L.Control()
L.control()
通过给定的选项创建一个控制。

Options

选项类型默认值描述
positionString'topright'控制初始的位置(在地图的某一角)。参见 control positions.

Methods

方法返回值描述
setPosition( <String> position )this设置控制的位置。参见 control positions.
getPosition()String返回控制的当前位置。
addTo( <Mapmap )this将控制添加到地图上。
removeFrom( <Mapmap )this将控制从地图上移除。
getContainer()HTMLElement返回 the HTML container of the control.

Control Positions(控制的位置)

Control positions (map corner to put a control to) are set using strings. Margins between controls and the map border are set with CSS, so that you can easily override them.

Position描述
'topleft'地图的左上角。
'topright'地图的右上角。
'bottomleft'地图的左下角。
'bottomright'地图的右下角。

下面讲下如何创建一个自定义控件

基本模板:

复制代码
L.Control.XXX= L.Control.extend({
    //在此定义参数    
options: {
},
//在此初始化 initialize:
function (options) { L.Util.extend(this.options, options); }, onAdd: function (map) { //可在此添加控件内容 } });
复制代码

以此模板创建一个简单图例控件

复制代码
L.Control.Legend = L.Control.extend({
    options: {
        position: 'topright' //初始位置

    },
    initialize: function (options) {
        L.Util.extend(this.options, options);

    },
    onAdd: function (map) {
//创建一个class为leaflet-control-clegend的div
this._container = L.DomUtil.create('div', 'leaflet-control-clegend');
//创建一个图片要素
var legendimg = document.createElement('img'); legendimg.id = 'leaflet-control-clegend'; legendimg.type = 'img'; legendimg.src = "../../Content/legend.png"; this._legendimg = legendimg; //创建一个关闭控件的按钮 var closebutton = document.createElement('a'); closebutton.id = 'leaflet-control-geosearch-close'; closebutton.className = 'glyphicon glyphicon-remove'; this._closebutton = closebutton; this._container.appendChild(this._closebutton); this._container.appendChild(this._legendimg); //注册关闭事件 L.DomEvent.addListener(this._closebutton, 'click', this._onCloseControl, this); return this._container; }, _onCloseControl: function () { this._map.options.Legend = false; this.removeFrom(this._map); }, });

复制代码

在定义一些样式后效果如下

高级一点可以定义如下扁平样式的:

 

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值