How to remove marker to Leaflet map in angular component

1.8k views Asked by At

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();
  });

});
1

There are 1 answers

1
kboul On

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