Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9859

How to remove previous layer when draw new?

Current behaviour of Draw plugin is add every new drawing layer to the map:

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'marker') {
        // Do marker specific actions
    }

    // Do whatever else you need to. (save to db, add to map etc)
    map.addLayer(layer);
});

but how to improve this code to get it remove every previous layer when user draw new one? I can't understand how to call: map.removeLayer(layer); and say it that I want to remove previous, but not current layer.

Upvotes: 1

Views: 2688

Answers (1)

ghybs
ghybs

Reputation: 53185

Assuming you want to remove all layers on map, you could use a code similar to that one at the beginning of your "draw:created" event listener:

map.eachLayer(function (layer) {
  map.removeLayer(layer);
});

(but I think that would also remove your Tile Layers, so maybe you should add some checks in there)

Should you use an intermediate drawnItems Feature Group, you could also simply use the .clearLayers() method:

drawnItems.clearLayers();

Upvotes: 3

Related Questions