How can I remove the drawing layer in leaflet.draw?

11,744

Solution 1

Since you're adding to featureGroup, which you say works, you should be removing from featureGroup too. Calling featureGroup.removeLayer(e.layer) or featureGroup.removeLayer(layer) (because layer holds a reference to e.layer) should work.

Here's a working example on Plunker: http://plnkr.co/edit/kPvYbH?p=preview

In my opinion the only conclusion can be that your event isn't firing or you're having some sort of weird scoping issue but that can easily be debugged:

$("a.cancelD").on("click", function() {
    console.log('Click fired!'); // Seeing this in your console, event works
    console.log(featureGroup); // Should return featureGroup instance, scope ok
    console.log(e.layer); // Should return polygon instance, scope ok

    // If all of the above works, this should too
    featureGroup.removeLayer(e.layer);
});     

Solution 2

I had this same issue. For me following solution worked,

featureGroup.clearLayers(e.layer);

Hope this will help someone

Solution 3

Alternatively, you can simply call .clearLayers() on your featureGroup layer that you created to hold all drawings.

Share:
11,744
oOo--STAR--oOo
Author by

oOo--STAR--oOo

Perfectionist.

Updated on July 23, 2022

Comments

  • oOo--STAR--oOo
    oOo--STAR--oOo almost 2 years

    With leaflet.js using leaflet.draw.js after using the draw tool to draw one of the shapes on a custom map. I have a form that pops up which says save or cancel. If the user presses cancel, then I want the drawing to be deleted. For example I was drawing a rectangle.

    Here is my current source

    map.on('draw:created', function(e) {
        var layer = e.layer;
        var type = e.layerType;
    
        $("#add-drawing").fadeIn(500);
    
        featureGroup.addLayer(e.layer); // Adds rectangle
    
        $("a.cancelD").on("click", function() {
            $("#add-drawing").fadeOut(500);
    
            // THESE ARE THE METHODS I HAVE TRIED TO REMOVE THE RECTANGLE
            map.removeLayer(layer);
            featureGroup.removeLayer(layer);
            map.removeLayer(e);
            featureGroup.removeLayer(e);
        });     
    });
    

    None of this seems to be working. I can use the toolbox to remove the layer, but then I won't have any information submitted in the form I wish to submit.

    How can I remove objects that I have drawn when pressing the cancel button on a form?