0

I am using leaflet on an Angular componenent and I am showing a marker when user click on map from esri-leaflet reverse geocoding, I want to remove previous markers added when user click.

this is my code:

    map.on('click', <LeafletMouseEvent>(e) => {

  geocodeService.reverse().latlng(e.latlng).run( (error, result) => {

    if (error) {
      return;
    }

    L.marker(result.latlng).addTo(map).bindPopup(result.address.Match_addr).openPopup();
  });

});
kboul
  • 13,836
  • 5
  • 42
  • 53
danny36
  • 131
  • 2
  • 11
  • 1
    Does this help? https://stackoverflow.com/questions/9912145/leaflet-how-to-find-existing-markers-and-delete-markers – wlf Sep 17 '20 at 11:11

1 Answers1

2

Store the marker in a variable and then remove the marker from the map after you click again on the map before adding the new one.

...
marker;
...
 map.on("click", (e) => {
  new ELG.ReverseGeocode().latlng(e.latlng).run((error, result) => {
    if (error) {
      return;
    }
    if (this.marker && map.hasLayer(this.marker))
      map.removeLayer(this.marker);

    this.marker = L.marker(result.latlng)
      .addTo(map)
      .bindPopup(result.address.Match_addr)
      .openPopup();
  });
});

Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
  • Hi, Esri refuses my requests because "499 Token Required" error. do you know where can I put my esri apikey? I couldn't find where to write it. – Tim's Dec 18 '22 at 12:01