1
votes

I added a layer group to my map:

L.layerGroup([marker1, marker2]).addTo(map);

before however, i tried doing: var myLayer = L.layerGroup([marker1, marker2]); but then I could never get it to add to the map

I want to remove the layergroup later on I've tried

  //map.removeLayer(LevelOneMarkers);

  //L.layerGroup([marker1, marker2]).removeLayer([marker1, marker2]);

  map.removeLayer([marker1, marker2]);

but non of those seem to work. am I missing something? I'm trying to follow

http://leafletjs.com/examples/layers-control.html

1

1 Answers

4
votes

You were mostly there.

To create a series of markers and add it to a layerGroup and add that to the map:

var marker1 = new L.marker([51.5, -0.09]);
var marker2 = new L.marker([52, -0]);

var markers = L.layerGroup([marker1, marker2]);
map.addLayer(markers);

To remove that layerGroup from the map:

map.removeLayer(markers);  //this takes the name of the layerGroup as the argument

References:

Leaflet API for LayerGroup

Bug fix so that removeLayer works on LayerGroups

JSFiddle: Here's a working JSFiddle. Notice how it doesn't show anything because it removes the layerGroup AFTER adding it. Comment out the removeLayer line to see the markers.