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

I wrote a Leaflet user control. This is some kind of legend that can be added for each layer. The control itself has a close button to remove it from the map (for example, a pop-up window). The control can be added by clicking the button. My problem is that the user can add the same control to the map several times. So I need to check if this particular control has already been added to the map, and if so, do not add it again.

I create a control for each level by passing some parameters

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

and add it to my map when you click

 control.addTo(map); 

Now imagine that the control has a closed button and can be closed. Now, if the user clicks the button again, I want to add a control, if it is not already on the map - something like this (hasControl pseudocode, there is no afaik there)

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

For simplicity, I made an example when I create a zoom control and add it twice here .

+7
leaflet
source share
1 answer

The easiest way is to check for the _map property in 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 when using the _map property, keep in mind that the _ property prefix implies that this is a private property that you usually should not use. It could be changed or deleted in future versions of the Flyer. You will not come across this if you use the following approach:

Attaching the link of your custom control to the 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 the link to your map instance as follows:

 if (map.customControl) { ... } 

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

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

This will work as follows:

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

Here is a demonstration of the concept on Plunker: http://plnkr.co/edit/nH8pZzkB1TzuTk1rnrF0?p=preview

+10
source share

All Articles