The markers drawn on leaflet.draw are not deleted after removing layer

1k Views Asked by At

I created a simple app to add points using leaflet draw. If the user cancel de dialog the drawn layer is removed. However, when the next marker is drawn, the previous cancelled ones appear again. Here is the pice of code:

// Create Leaflet Draw Control for the draw tools and toolbox
var drawControl = new L.Control.Draw({
  draw : {
    polygon : false,
    polyline : false,
    rectangle : false,
    circle : false,
    circlemarker: false
  },
  edit : false,
  remove: false
});

// Boolean global variable used to control visiblity
var controlOnMap = false;

// Create variable for Leaflet.draw features
var drawnItems = new L.FeatureGroup();

// Function to add the draw control to the map to start editin
function startEdits(){
  if(controlOnMap == true){
    map.removeControl(drawControl);
    controlOnMap = false;
  }
  map.addControl(drawControl);
  controlOnMap = true;
};

// Function to remove the draw control from the map
function stopEdits(){
  if(controlOnMap == true){
    map.removeControl(drawControl);
    controlOnMap = false;
  }else{
    alert("Edition mode is already stopped")
  };
};

// Use the jQuery UI dialog to create a dialog and set options
var dialog = $("#dialog").dialog({
  autoOpen: false,
  height: 600,
  width: 500,
  modal: true,
  position: {
    my: "center center",
    at: "center center",
    of: "#map"
  },
  buttons: {
    "Add": setData,
    "Cancel": function() {
      dialog.dialog("close");
      map.removeLayer(drawnItems);
    }
  },
  close: function() {
    dialog.dialog("close");
    map.removeLayer(drawnItems);
  }
});

Is there a function to remove the drawn features or similar?

2

There are 2 best solutions below

0
On BEST ANSWER

You have also to clear the drawnItems group:

drawnItems.clearLayers();
map.removeLayer(drawnItems);

A newer drawing lib is: Geoman.io

0
On

Just now I found this solution:

    drawnItems.eachLayer(
        function(l){
            drawnItems.removeLayer(l);
    });

But Falke design's answer is quite more fancy. Thank you!