找出传单控件是否已添加到地图中

时间:2015-10-15 11:03:53

标签: leaflet

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

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

var control = L.control.customControl(mylayer);

并点击按钮

将其添加到我的地图中
control.addTo(map);

现在假设控件有一个关闭按钮,可能会关闭。现在,如果用户再次单击该按钮,我只想添加控件,如果它还没有在地图上 - 就像这样(hasControl是伪代码,没有这样的功能)

if(!(map.hasControl(control))) {
    control.addTo(map);
}

为简单起见,我做了一个示例,我创建了一个缩放控件并将其添加两次here

1 个答案:

答案 0 :(得分:14)

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

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

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

map.addControl(customControl);

console.log(customControl._map); // returns map instance

但请注意,在使用_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;
    }
});

现在您可以检查地图实例上的引用,如下所示:

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

相关问题