2

Every time the location updates it places a new marker instead of moving the existing one. I just wanted there to be one marker on the screen instead of a new one placed every time the application updates its position (ignore the max age and frequency, I was testing something and I know they aren't the problem). Thanks in advance.

(code to load the map)

    function onLocationFound(e) {

                                var marker= L.icon({iconUrl: 'greendot.png'});
    var radius = e.accuracy /2;

    L.marker(e.latlng, {icon: marker}).addTo(map).bindPopup("You are within " + radius + " meters from this point").openPopup();



                                  }

    function onLocationError(e) {
        alert(e.message);
    }


    map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);

    map.locate({watch: true, setView: true, maxZoom: 16, enableHighAccuracy: true, maximumAge:10000, frequency: 1});

Edit: I have tried several solutions and the marker still doesnt move, it just adds a new one. Any ideas?

min222002
  • 21
  • 6

1 Answers1

2

Instead of creating a new marker each time, you could update an existing one:

var marker = L.icon({iconUrl: 'greendot.png'});
var movingMarker = L.marker([0,0], 0, {icon: marker}).addTo(map);

function onLocationFound(e) {
    var radius = e.accuracy /2;
    movingMarker.setLatLng(e.latlng);
    movingMarker.unbindPopup();
    movingMarker.bindPopup("You are within " + radius + " meters from this point")
    movingMarker.redraw();
}

function onLocationError(e) {
    alert(e.message);
}

map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);

map.locate({watch: true, setView: true, maxZoom: 16, enableHighAccuracy: true, maximumAge: 10000});

I just found a similar question (with a similar answer): update marker location with leaflet API

Community
  • 1
  • 1
Håvard Tveite
  • 215
  • 2
  • 7