L.Control
The base class for all leaflet controls. Inherited from the IControl interface. You can add controls like this:
control.addTo(map);
// the same as
map.addControl(control);
Constructor
Constructor usage descriptionL.Control( <Control options> options? ) |
new L.Control(…) L.control(…) |
Creates a control with the given options. |
Options
Option Type Default Value Descriptionposition |
String |
'topright' |
Controls the initial position (in a corner of the map). See also control positions . |
Methods
Method return value descriptionsetPosition( <String> position ) |
this |
Sets the location of the control. See also control positions . |
getPosition() |
String |
Returns the current position of the control. |
addTo( <Map> map ) |
this |
Add controls to the map. |
removeFrom( <Map> map ) |
this |
Remove control from the map. |
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 Description'topleft' |
upper left corner of the map. |
'topright' |
top right corner of the map. |
'bottomleft' |
Bottom left corner of the map. |
'bottomright' |
bottom right corner of the map. |
Here's how to create a custom control
Basic template:
L.Control.XXX= L.Control.extend({ //Define parameters here
options: { },
//Initialize here 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); }, });
在定义一些样式后效果如下
高级一点可以定义如下扁平样式的: