coderabbit coderabbit - 2 months ago 21
Javascript Question

How to remove Overlays from L.control in leaflet

On the client Im getting a bunch of polygons from a postgres database and then I am adding them as an overlay into a layers control. At the moment this is happening via say a menu click, and each time it adds another 'Polygon' checkbox in the control. I need to obviously clear first any old overlays and refresh with a new set of 'Polygon' overlays. How can I remove it programmatically before adding a new overlay?

var controlLayers = L.control.layers(baseMaps).addTo(map);


$.getJSON('/db/getPolys', function (geojsonFeatures) {
console.log('returned polys...',geojsonFeatures.features);
if(geojsonFeatures.features == null){
alert('No polygons where found');
}else{
geojsonLayer = L.geoJson(geojsonFeatures,{
onEachFeature: drawStep1Polys
});

// need to remove before adding anything
// if (geojsonLayer exists){
// controlLayers.removeLayer(geojsonLayer);
// }
controlLayers.addOverlay(geojsonLayer, 'Polygons');
}
});

Answer

controlLayers.removeLayer(geojsonLayer)

Remove the given layer from the control.

(note that you will have to keep reference of your previous layers)