Find out if a leaflet control has already been added to the map

前端 未结 1 1556
温柔的废话
温柔的废话 2021-02-20 13:55

I wrote a custom Leaflet control. It\'s some kind of legend that may be added for each layer. The control itself has a close button to remove it from the map (like a popup). Th

相关标签:
1条回答
  • 2021-02-20 14:21

    Easiest way is to check for the existence of the _map property on your control instance:

    var customControl = new L.Control.Custom();
    
    console.log(customControl._map); // undefined
    
    map.addControl(customControl);
    
    console.log(customControl._map); // returns map instance
    

    But please keep in mind, when using the _map property, that the _ prefix of the property implies that it's a private property, which you are normally not supposed to use. It could be changed or removed in future versions of Leaflet. You're not going to encounter that if you use the follow approach:

    Attaching a reference of your custom control to your L.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;
        }
    });
    

    Now you can check for the reference on your map instance like so:

    if (map.customControl) { ... }
    

    Or create a method and include it in L.Map:

    L.Map.include({
        hasCustomControl: function () {
            return (this.customControl) ? true : false;
        }
    });
    

    That would work like this:

    var customControl = new L.Control.Custom();
    
    map.addControl(customControl);
    
    map.hasCustomControl(); // returns true
    
    map.removeControl(customControl);
    
    map.hasCustomControl(); // returns false
    

    Here's a demo of the concept on Plunker: http://plnkr.co/edit/nH8pZzkB1TzuTk1rnrF0?p=preview

    0 讨论(0)
提交回复
热议问题