coderabbit
coderabbit

Reputation: 143

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');
              }
});

Upvotes: 6

Views: 10466

Answers (2)

coderabbit
coderabbit

Reputation: 143

Thanks, btw, this was the final code:

         var group;
         $.getJSON('/FIMS/getPolys', function (geojsonFeatures) {
              console.log('returned polys...',geojsonFeatures.features);
              if(geojsonFeatures.features == null){
                  var message = 'No polygons where found'; 
                  alert(message); 
              }else{

                  if (group) {
                      controlLayers.removeLayer(group);
                  }

                  group = L.geoJson(geojsonFeatures, {
                      onEachFeature: drawStep1Polys
                  }).addTo(map);

                  controlLayers.addOverlay(group, 'Polygons');
                  map.fitBounds(step1Bounds);
              }
          });

Upvotes: 1

ghybs
ghybs

Reputation: 53185

controlLayers.removeLayer(geojsonLayer)

Remove the given layer from the control.

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

Upvotes: 6

Related Questions