How can I remove last shape layer when creating new one in lefalet

156 Views Asked by At

According to this codesandbox I'm using to to generate a map on react and I have implemented the drawer plugin. here I want to delete the last shape I have added to the map and create and show the new map instead of the last shape. Is there nay performant way of doing that?

1

There are 1 best solutions below

0
On BEST ANSWER

Store the last layer in a variable in the create event:

var lastLayer = null;
map.on(L.Draw.Event.CREATED, function (e) {
      var type = e.layerType,
        layer = e.layer;

      if (type === "marker") {
        const { lat, lng } = layer._latlng;
        console.log(lat, lng);
      }

      if (type === "rectangle") {
        const latlngs = layer._latlngs;
        let thisPpp = "";
        latlngs[0].map((item) => {
          return (thisPpp += `LatLng(${item.lat}, ${item.lng}),`);
        });
      }

      lastLayer = layer; // <---------------
      drawnItems.addLayer(layer);
});

And then you can remove the last layer with:

if(lastLayer){
   lastLayer.remove();
}