Warm tip: This article is reproduced from stackoverflow.com, please click
javascript leaflet

Leaflet updating marker disappears for as long as it shows

发布于 2020-04-11 22:23:53

I'm using leaflet and I'm working on a script that updates marker positions every X seconds. Every time I update the marker it disappears for as long as it shows up on the map. Which is the same value as the interval for the updater. In the example below the interval is 1000ms, which means it shows up for 1000ms and disappears for 1000ms.

If we change the value the disappearing time will change with it. It is directly linked. What I want to accomplish is updating a marker without it disappearing or only disappearing for a

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
</head>

<body>
  <div id="mapid" style="width: 600px; height: 400px;"></div>
  <script>
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);

    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/">OpenStreetMap</a> contributors, ' +
        '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      id: 'mapbox/streets-v11'
    }).addTo(mymap);

    var marker = L.marker([51.5, -0.09]).addTo(mymap);

    setInterval(function() {
      var markerPos = marker.getLatLng();
      marker.setLatLng([markerPos.lng + 0.001, markerPos.lat]);
    }, 1000);
  </script>
</body>

</html>
Questioner
hiwave
Viewed
39
peeebeee 2020-02-02 19:45

Your code to update the marker reverses the lat/lng every time it's called. So every other time the position is updated to something that's outside your map. Try this (or modify to increment the lng instead of the lat if that's what's needed)

var markerPos = marker.getLatLng();
marker.setLatLng([markerPos.lat + 0.001, markerPos.lng]);