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

标签 javascript jquery leaflet marker

我正在制作传单 map 和标记。

我从 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() 修改其位置,而不是在每次更新时实例化新标记。方法。

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

可能稍微棘手的部分是同时管理多个标记。您需要某种识别手段来知道要更新哪一个。我假设这是您的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);

关于javascript - 如何每 5 秒更新一次传单标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48900378/

相关文章:

javascript - Meteor 基础应用 : ReferenceError: Entries is not defined

javascript - Sinon spy 使用两种不同的回调签名

javascript - Grails Controller 的值打破了gsp中的javascript

javascript - 通过字符分隔字符串

javascript - 几个延迟的动画不起作用

javascript - 如何关闭所有弹出窗口?

javascript - 将传单控件放置在 map 之外

javascript - Chart.js - 折线图中的 2 个数据集总是显示工具提示?

javascript 包含无法在 chrome 上运行

javascript - 根据为传单提供的地址获取纬度和经度