1

I have a Leaflet OpenStreetMap map where I set a new marker. I want the marker to move, which would mean clearing all previous markers, and adding a new one. Currently new clicks just result in new markers, with more than one staying on the map.

How can I clear all markers upon clicking again?

initmap();
var home = new L.LayerGroup();

map.on('click', function(e) {
  // clear all markers here somehow
  document.getElementById("latFld").value = e.latlng.lat;
  document.getElementById("lngFld").value = e.latlng.lng;
  L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);
  });

Edit:

My original markers did not belong to a group.

L.marker([43.653409, -79.384112]).bindPopup('Original Home').addTo(map);

Regardless of the LayerGroup into a variable, I was asking if there was a way to clear all markers regardless. It is not a duplicate.

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
Rich_F
  • 1,830
  • 3
  • 24
  • 45
  • Possible duplicate of [deleting Leaflet realtime markers](https://stackoverflow.com/questions/49498385/deleting-leaflet-realtime-markers) – ghybs Apr 18 '18 at 01:50

1 Answers1

1

Shoved my markers into a layerGroup so I can use that for clearing:

var mymarkers = L.layerGroup([
    L.marker([43.677681,-79.389943]).bindPopup('Some place'),
    L.marker([<%= @mylat %>,<%= @mylon %>]).bindPopup('Original Home')
]);

L.control.layers(mymarkers).addTo(mymap);

mymap.on('click', function(e) {
    mymarkers.clearLayers();
    document.getElementById("latFld").value = e.latlng.lat;
    document.getElementById("lngFld").value = e.latlng.lng;
    L.marker([e.latlng.lat,e.latlng.lng]).bindPopup('New ome').addTo(mymarkers);
    $('#update').html("Values updated");
});

I was expecting an object that automatically held all markers, but it wasn't there. So I had to assign then to one.

Rich_F
  • 1,830
  • 3
  • 24
  • 45