我写了一个自定义 Leaflet 控件。这是可以为每一层添加的某种图例。控件本身有一个关闭按钮,可将其从 map 中移除(如弹出窗口)。
可以通过单击按钮来添加控件。
我的问题是用户可能会多次向 map 添加相同的控件。所以我需要测试这个特定控件是否已经添加到 map 中,如果是,请不要再次添加。
我为每一层创建一个控件,传递一些选项
var control = L.control.customControl(mylayer);
并在按钮单击时将其添加到我的 map 中
control.addTo(map);
现在想象控件有一个关闭按钮并且可能被关闭。现在,如果用户再次单击该按钮,我只想添加尚未在 map 上的控件 - 类似这样(hasControl 是伪代码,没有这样的功能)
if(!(map.hasControl(control))) {
control.addTo(map);
}
为简单起见,我做了一个示例,我创建了一个缩放控件并添加了两次 here .
最佳答案
最简单的方法是检查 _map
是否存在您的控件实例上的属性:
var customControl = new L.Control.Custom();
console.log(customControl._map); // undefined
map.addControl(customControl);
console.log(customControl._map); // returns map instance
但请记住,在使用
_map
时属性(property),即 _
属性的前缀意味着它是私有(private)属性,通常不应该使用它。它可以在 Leaflet 的 future 版本中更改或删除。如果您使用以下方法,您将不会遇到这种情况:将自定义控件的引用附加到您的
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;
}
});
现在您可以像这样检查 map 实例上的引用:
if (map.customControl) { ... }
或者创建一个方法并将其包含在
L.Map
中:L.Map.include({
hasCustomControl: function () {
return (this.customControl) ? true : false;
}
});
这将像这样工作:
var customControl = new L.Control.Custom();
map.addControl(customControl);
map.hasCustomControl(); // returns true
map.removeControl(customControl);
map.hasCustomControl(); // returns false
这是 Plunker 上的概念演示:http://plnkr.co/edit/nH8pZzkB1TzuTk1rnrF0?p=preview
关于leaflet - 查明是否已将传单控件添加到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146809/