1

I've added a layer to a map via Leaflet. It's actually a circle around a point. This gets added perfectly. I'd like for it to be removed when I click a certain button. Here's how I'm creating the circle. I'm adding it to a group, as there are instances where there are multiple circles and I'd like to remove them all at once.

    var five_mile = L.circle([latitude,longitude], 11046,{
    fillColor:'#1d5492',
  fillOpacity:'0.3',
  stroke:false,
  clickable:false
})
 map_object.addLayer(five_mile);
 assetLayerGroup.addLayer(five_mile);
 var layers = assetLayerGroup.getLayers();
  console.log(layers);

The console log shows me that there is layer data in the assetLayerGroup.

To remove the layer, I'm doing this:

$('#remove_cir').click(function() {
  assetLayerGroup.clearLayers();
});

#remove_cir is the ID for the button I click to remove the circles in the group. There are no errors thrown when I click this, but the circle isn't removed.

What am I missing?

1

I think its because you are adding the layer twice, once directly to the map (if that's what map_object is), and then again to the layer group.

This should work:

$('#remove_cir').click(function() {
    assetLayerGroup.eachLayer(function(layer) { map_object.removeLayer(layer) });
    assetLayerGroup.clearLayers();
});

But it would be better to add your layer and layergroup to the map in a different way.

// on instantiation add it to the map as an empty layer group
assetLayerGroup = L.layerGroup([]).addTo(map_object); 

// then add layers to the layer group, but not to the map
// with this, clear layers should work on the layer group as you have above
assetLayerGroup.addLayer(five_mile);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.