Skip to content
Advertisement

Remove previous markers before update marker in leaflet map?

Here I am trying to update the markers on map upon successful ajax request but I am being unable to remove previously added markers before adding new one. How can I do it here ?

   $(document).ready(function(){
    var element = document.getElementById('map');
    element.style = 'height:600px;';
    map = L.map(element);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    var target = L.latLng('33.812358', '79.324126');
    
    var locations = [
      ["1", lat, lng}],
    ];
    for (var i = 0; i < locations.length; i++) {
      marker = new L.marker([locations[i][1], locations[i][2]])
        .bindPopup(locations[i][0])
        .addTo(map);
    }
    map.setView(target, 14);
    L.marker(target).addTo(map);
    
     $('.click').click(function(e) {
            url=$(this).attr('url');
            $.ajax({
            url: url,
            type: 'GET',
            success: function (data) {
              var locations = [["1", 29.72184, 90.303634],];
                for (var i = 0; i < locations.length; i++) {
                  marker = new L.marker([locations[i][1], locations[i][2]])
                    .bindPopup(locations[i][0])
                    .addTo(map);
                }
                map.setView(target, 14);
                var markers = L.markerClusterGroup();
                markers.clearLayers(map._layers);          
                L.marker(target).addTo(map);

Advertisement

Answer

Here’s an example, that stores the Marker inside each location Object of your locations Array.

Additionally, create two functions, drawLocationsToMap and removeLocationsFromMap.

const Map = L.map('map');

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
    'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
  id: 'mapbox/streets-v11',
  tileSize: 512,
  zoomOffset: -1
}).addTo(Map);


let locations = [{
    lat: 45.8150,
    lng: 15.9819,
    content: "<b>Zagreb</b><br>Description..."
  },
  {
    lat: 43.5081,
    lng: 16.4402,
    content: "<b>Split</b><br>Some descrip..."
  },
  {
    lat: 42.6507,
    lng: 18.0944,
    content: "<b>Dubrovnik</b><br>Descript..."
  },
];

const drawLocationsToMap = () => {
  locations.forEach(loc => {
    if (!loc.Marker) {
      loc.Marker = new L.marker([loc.lat, loc.lng]);
      loc.Marker.bindPopup(loc.content);
    }
    loc.Marker.addTo(Map);
  });
};

const removeLocationsFromMap = () => {
  locations.forEach(loc => {
    Map.removeLayer(loc.Marker)
  });
};

Map.setView([locations[0].lat, locations[0].lng], 5);

// Draw current locations to map
drawLocationsToMap();

// Add new marker
// (i.e: on click or AJAX success. I'll use timeout for demo)
setTimeout(() => {

  // Remove all locations from map!
  removeLocationsFromMap(); 
  
  // Update the locations array with a single location
  locations = [{
    lat: 44.8666,
    lng: 13.8496,
    content: "Pula, Croatia"
  }]; 
  
  // Draw updated locations!
  drawLocationsToMap();
  
}, 3000);
#map {
  height: 190px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />

<div id="map"></div>

<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement