【Leafletjs】5.L.Control 自定義一個Control


L.Control

所有leaflet控制的基礎類。繼承自IControl接口。 你可以這樣添加控件:

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

構造器

構造器 使用 描述
L.Control( <Control options> options? ) new L.Control()
L.control()
通過給定的選項創建一個控制。

Options

選項 類型 默認值 描述
position String 'topright' 控制初始的位置(在地圖的某一角)。參見 control positions.

Methods

方法 返回值 描述
setPosition( <String> position ) this 設置控制的位置。參見 control positions.
getPosition() String 返回控制的當前位置。
addTo( <Map> map ) this 將控制添加到地圖上。
removeFrom( <Map> map ) 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); }, });

在定義一些樣式后效果如下

高級一點可以定義如下扁平樣式的:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM