[英]How to add [UP] -3 [DOWN] controls to switch between layers on a custom map?
我為你創建了一個工作控制器(但它不是設計的):
L.LayerControl = L.Control.extend({
options: {
position: 'topright',
layerIdx: 0,
//control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
},
initialize: function(layers, options) {
this.layers = layers;
L.setOptions(this, options);
},
onAdd: function (map) {
this.map = map;
var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control layercontrol');
var buttonUp = L.DomUtil.create('a', '', container);
buttonUp.innerHTML = '^';
this.text = L.DomUtil.create('a', '', container);
this.text.innerHTML = this.layers[this.options.layerIdx].name;
this.text.style.fontWeight = '900';
var buttonDown = L.DomUtil.create('a', '', container);
buttonDown.innerHTML = 'v';
L.DomEvent.disableClickPropagation(container);
L.DomEvent.on(buttonUp, 'click', this._clickUp, this);
L.DomEvent.on(buttonDown, 'click', this._clickDown, this);
this._removeAllLayers();
this.map.addLayer(this.layers[this.options.layerIdx].layer);
return container;
},
_clickUp : function () {
if(this.layers.length -1 > this.options.layerIdx){
this.map.fire('layercontrolUp', {layer: this.layers[this.options.layerIdx].layer, name: this.layers[this.options.layerIdx].name});
this.options.layerIdx++;
this.text.innerHTML = this.layers[this.options.layerIdx].name;
this._removeAllLayers();
this.map.addLayer(this.layers[this.options.layerIdx].layer);
}
},
_clickDown : function () {
if(0 < this.options.layerIdx){
this.map.fire('layercontrolDown', {layer: this.layers[this.options.layerIdx].layer, name: this.layers[this.options.layerIdx].name});
this.options.layerIdx--;
this.text.innerHTML = this.layers[this.options.layerIdx].name;
this._removeAllLayers();
this.map.addLayer(this.layers[this.options.layerIdx].layer);
}
},
_removeAllLayers: function(){
//removing all layers from the map where added from the control
this.layers.forEach(function(controlLayer){
this.map.removeLayer(controlLayer.layer);
});
}
});
var fg1 = new L.FeatureGroup();
fg1.addLayer(L.marker([51.5, -0.09]).bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup());
var fg2 = new L.FeatureGroup();
fg2.addLayer(L.circle([51.508, -0.11], 500, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).bindPopup("I am a circle."));
var fg3 = new L.FeatureGroup();
fg3.addLayer(L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).bindPopup("I am a polygon."));
var layerControlLayers = [
{
name: 'KG1',
layer: fg1
},
{
name: 'KG2',
layer: fg2
},
{
name: 'EG',
layer: fg3
},
]
//layerIdx: start counting with 0 = KG1
new L.LayerControl(layerControlLayers, {layerIdx: 2}).addTo(map)
map.on('layercontrolUp', function(e){
console.log(e);
});
map.on('layercontrolDown', function(e){
console.log(e);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.