Leaflet 了解是否已将传单控件添加到地图中

Leaflet 了解是否已将传单控件添加到地图中,leaflet,Leaflet,我写了一个自定义的单张控件。这是一种可以为每一层添加的图例。控件本身有一个关闭按钮,可将其从地图中删除(如弹出窗口)。 可以通过单击按钮添加控件。 我的问题是,用户可能会多次向地图添加相同的控件。所以我需要的是测试这个特定的控件是否已经添加到映射中,如果已经添加了,请不要再添加它 我为每个层创建一个控件,传递一些选项 var control = L.control.customControl(mylayer); 然后单击按钮将其添加到我的地图 control.addTo(map); 现在想象

我写了一个自定义的单张控件。这是一种可以为每一层添加的图例。控件本身有一个关闭按钮,可将其从地图中删除(如弹出窗口)。 可以通过单击按钮添加控件。 我的问题是,用户可能会多次向地图添加相同的控件。所以我需要的是测试这个特定的控件是否已经添加到映射中,如果已经添加了,请不要再添加它

我为每个层创建一个控件,传递一些选项

var control = L.control.customControl(mylayer);
然后单击按钮将其添加到我的地图

control.addTo(map);
现在想象一下,控件有一个关闭按钮,可以关闭。现在,如果用户再次单击按钮,我只想在控件不在地图上的情况下添加它-类似这样的东西(hasControl是伪代码,没有这样的函数)


为了简单起见,我举了一个例子,创建了一个缩放控件并添加了两次。

最简单的方法是检查控件实例上是否存在
\u map
属性:

var customControl = new L.Control.Custom();

console.log(customControl._map); // undefined

map.addControl(customControl);

console.log(customControl._map); // returns map instance
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;
    }
});
但请记住,在使用
\u map
属性时,属性的
\u
前缀意味着它是一个私有属性,您通常不应该使用它。它可以在未来版本的传单中更改或删除。如果使用以下方法,您将不会遇到这种情况:

将自定义控件的引用附加到
L.Map
实例:

var customControl = new L.Control.Custom();

console.log(customControl._map); // undefined

map.addControl(customControl);

console.log(customControl._map); // returns map instance
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;
    }
});
现在,您可以检查地图实例上的引用,如下所示:

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上概念的演示:

任何能让你的船漂浮的东西:)但请记住,当使用
\u map
属性时,属性的
\u
前缀意味着它是私人财产,通常你不应该使用它。它可以在未来版本的传单中更改或删除。第二种方法不会遇到这个问题。在我的答案中添加了这个,只是为了完整:)好吧,现在我仔细看了第二个版本。我想如果我有多个customControl,可能会有问题,不是吗?类似于
var customControl1=新的L.Control.Custom(someOptions);var customControl2=新的L.Control.Custom(其他选项)-如果我现在同时添加并删除第一个,
hasCustomControl
将返回false。您可以轻松编写一些逻辑,使其处理多个实例。不要将实例存储为直接属性,而是存储在一个对象中,这样您就可以添加多个,类似这样:如果您对控件的添加/删除有严格的控制权,那么您可以在控制对象上设置自己的变量,指示它是否存在于地图上。它的工作原理与._map类似,但它是您自己的变量,不受传单开发人员的更改。而且因为它将是每个控件,而不是每个映射,所以您不会遇到“第二个版本”的问题。