[GIS] How to access array inside of Leaflet LayerControl

leaflet

When you make a Leaflet LayerControl you first make an array of markers, then pass the array to the LayerControl constructor and add the LayerControl to the map, like this:

myLayerGroup = L.layerGroup(arMarker).addTo(map);

However, I want the markers in the Layer Group to change when the user pans the map. I have coded the appropriate event handler, like this:

map.on('dragend',this.onDragEnd);

I then pass the new extent of the map to the server side via Ajax, query the database and get back the markers that are within the new extent.

What I want to do next is add the new markers and delete the old markers that are not within the new extent. But in order to do that I have to access the array that I passed to the LayerControl. I don't want to just delete all the current markers and add the new markers because many of the new markers will also be the current markers.

Is there a way to access that array within the LayerControl, or do I just have to delete the LayerControl and start again?

Best Answer

But in order to do that I have to access the array that I passed to the LayerControl.

No, you don't. Just use the addOverlay and removeLayer methods of L.Control.Layer. Keep an external reference to the layers added to the control if you need.