如何每 5 秒更新一次传单标记

How to update leaflet markers for every 5 seconds

我正在制作传单地图和标记。

我正在从 JSON 获取标记 latlng 并正确显示它。

getLatLng()

function getLatLng() {
  var details = '/equipment/api/getLatLong';
  $.ajax({
    url: details,
    method: 'get'
  }).done(function(response) {

    $('.subSection').html('').append('<section><button type="button" onclick="hideEquipmentDetails()"><i class="fa fa-times"></i></button></section>');
    var equipmentDetails = response.data.filters;
    console.log(equipmentDetails)
    $.each(equipmentDetails, function(i, value) {
      L.marker([value.latitude, value.longitude]).addTo(map).bindPopup('<b><span> Name:</span>' + value.name + '</b>');
    })
  });
}

setInterval(function() {
  getLatLng();
}, 5000)

我是每5秒刷新一次方法

所以我需要在更新的 latlng 中显示标记,旧标记应该被隐藏。

setInterval(function() {
  //L.marker.setOpacity(0);
  //L.markerClusterGroup()
  //markers.clearLayers();
  //map.removeLayer(L.marker);
  //markers.removeLayer()
  //L.marker().removeTo(map);
  getLatLng();
}, 5000)

我尝试了所有方法来实现这一点,但我做不到。

还有其他方法吗?

否则我应该再定义一个数组来存储初始 latlng 值然后每次检查 latlng 是否更改(在这种情况下我可以只替换更新的 latlng 标记对吗?不需要每次都替换所有标记对吧?)

无需在每次更新时实例化一个新标记,您只需使用其 setLatLng() 方法修改其位置即可。

通常的实现是使用一个 "global" 标记变量(只在你的更新函数之外的范围内就足够了),在你的第一次迭代中将它初始化为一个标记,然后而不是实例化一个新的,只需修改其位置即可。

可能稍微棘手的部分是同时管理多个标记。您需要某种识别方式才能知道要更新哪个。我假设这是你的 value.name:

var markers = {}; // Dictionary to hold your markers in an outer scope.

function ajaxCallback(response) {
  var equipmentDetails = response.data.filters;
  $.each(equipmentDetails, function(i, value) {
    var id = value.name;
    var latLng = [value.latitude, value.longitude];
    var popup = '<b><span> Name:</span>' + id + '</b>';

    if (!markers[id]) {
      // If there is no marker with this id yet, instantiate a new one.
      markers[id] = L.marker(latLng).addTo(map).bindPopup(popup);
    } else {
      // If there is already a marker with this id, simply modify its position.
      markers[id].setLatLng(latLng).setPopupContent(popup);
    }
  });
}

$.ajax({
  url: details,
  method: 'get'
}).done(ajaxCallback);