我写了一个自定义的Leaflet控件.这是可以为每一层添加的某种图例.控件本身有一个关闭按钮,可以将其从地图中删除(如弹出窗口).可以通过单击按钮添加控件.我的问题是用户可能会多次向地图添加相同的控件.所以我需要的是测试这个特定的控件是否已经添加到地图中,如果是,请不要再添加它.
我为每个图层创建一个控件,传递一些选项
var control = L.control.customControl(mylayer);
Run Code Online (Sandbox Code Playgroud)
并在按钮单击时将其添加到我的地图
control.addTo(map);
Run Code Online (Sandbox Code Playgroud)
现在假设控件有一个关闭按钮,可能会关闭.现在,如果用户再次单击该按钮,我只想添加控件,如果它还没有在地图上 - 就像这样(hasControl是伪代码,有afaik没有这样的功能)
if(!(map.hasControl(control))) {
control.addTo(map);
}
Run Code Online (Sandbox Code Playgroud)
为简单起见,我做了一个例子,我在这里创建一个缩放控件并在此处添加两次.
iH8*_*iH8 15
最简单的方法是检查_map控件实例上是否存在属性:
var customControl = new L.Control.Custom();
console.log(customControl._map); // undefined
map.addControl(customControl);
console.log(customControl._map); // returns map instance
Run Code Online (Sandbox Code Playgroud)
但请记住,在使用_map属性时,属性的_前缀暗示它是私有属性,通常不应该使用它.它可以在Leaflet的未来版本中更改或删除.如果您使用以下方法,您将不会遇到这种情况:
将自定义控件的引用附加到您的L.Map实例:
L.Control.Custom = L.Control.extend({
options: {
position: 'bottomleft'
},
onAdd: function (map) {
// Add reference to map
map.customControl = this;
return L.DomUtil.create('div', 'my-custom-control');
},
onRemove: function (map) {
// Remove reference from map
delete map.customControl;
}
});
Run Code Online (Sandbox Code Playgroud)
现在,您可以检查地图实例上的参考,如下所示:
if (map.customControl) { ... }
Run Code Online (Sandbox Code Playgroud)
或者创建一个方法并将其包含在L.Map:
L.Map.include({
hasCustomControl: function () {
return (this.customControl) ? true : false;
}
});
Run Code Online (Sandbox Code Playgroud)
这将是这样的:
var customControl = new L.Control.Custom();
map.addControl(customControl);
map.hasCustomControl(); // returns true
map.removeControl(customControl);
map.hasCustomControl(); // returns false
Run Code Online (Sandbox Code Playgroud)
以下是Plunker概念的演示:http://plnkr.co/edit/nH8pZzkB1TzuTk1rnrF0?p = preview