Search code examples
leafletmarker

How to remove a marker from leaflet map


I have a marker in my leaflet map like

marker = new L.Marker([lat,lon],{icon:flagIcon,title: "Drage me to change your location"}).addTo(map);
              marker.dragging.enable();
              marker.on('dragend', function(e){
                  var coords = e.target.getLatLng();
                  var lat = coords.lat;
                  var lon = coords.lng;
                  console.log("Lat : "+lat+"  Lng: "+lon);
                  document.getElementById("lat").value=lat;
                  document.getElementById("long").value=lon;
                  document.getElementById("placeName").value="location on map";
                  updateAnchor();
                  map.panTo({lon:lon,lat:lat})
                  if(flag!=0){
                      map.removeLayer(cir);
                      cir = L.circle([lat,lon],circleOptions).addTo(map);
                      refreshMarkers(flag);
                   }
              });

If the marker is already exist i want to remove it and and a new one.For that i added a code like

if (marker) {
    map.removeLayer(marker); // remove
}

But i couldn't remove the older marker.How to solve this issue


Solution

  • The marker you're adding isn't the same object as the marker that's already on the map. If you want to be able to reference (eg to remove) a marker later, save a copy of the marker object in a global.

    var oldmarker;
    
    marker = <your code here>
    oldmarker = marker;
    

    Then

    if (map.hasLayer(oldmarker)) {
        map.removeLayer(oldmarker);
    }