Home javascript How to delete each previous label in leaflet.js, after adding a new...

How to delete each previous label in leaflet.js, after adding a new one?

Author

Date

Category

Tell me how to properly write code and delete previous tags in Leaflet?

mymap.on ("click", function (E) {
    Let NewMarker = New L.Marker ([e.latlng.lat, e.latlng.lng]);
    newmarker.addto (MYMAP);
  });

There is a constant addition of a new one, and you need to add only one. Thank you


Answer 1, Authority 100%

Initialize the marker to the subscription to the ‘Click’ event.
Then, if there is a layer of ‘newmarker’ on the map, we remove it.
After that, add a new marker.

let newmarker;
  MyMap.ON ('Click', Function (E) {
    if (MYMAP.HASLayer (Newmarker)) {
      MyMap.RemoveLayer (Newmarker);
    }
    newmarker = new l.marker ([e.latlng.lat, e.latlng.lng]);
    newmarker.addto (MYMAP);
  });

or can be done like this:

mymap.on ('Click', Function (E) {
  if (mymap.haslayer (this.Layer)) {
    mymap.removelayer (this.Layer);
  }
  this.Layer = New L.Marker ([e.latlng.lat, e.latlng.lng]);
  this.Layer.Addto (MyMap);
});

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions