且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-28 17:31:37

您无需在每次更新时都实例化新标记,只需使用其

Instead of instantiating a new marker on every update, you could simply modify its position using its setLatLng() method.

通常的实现是使用全局"标记变量(仅在更新函数之外的范围内就足够了),在第一次迭代时将其初始化为Marker,然后无需实例化新变量,只需修改其位置即可

The usual implementation is to use a "global" marker variable (just in a scope outside your update function is enough), initialize it to a Marker on your first iteration, then instead of instantiating a new one, simply modify its position.

可能比较棘手的部分是同时管理多个标记.您需要某种识别方式才能知道要更新哪个.我认为这是您的value.name:

The possibly slightly trickier part is to manage several markers at the same time. You need some sort of identification mean to know which one to update. I assume it is your 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);