How to update leaflet markers for every 5 seconds

无人久伴 提交于 2019-12-08 09:03:45

问题


I am working on a Leaflet map and markers.

I am getting markers latlng from JSON and showing it correctly.

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)

I am refreshing the method for every 5 seconds.

So I need to show the markers in updated latlng and old markers should be hidden.

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

I tried every options to achieve this but I couldn't.

Is there any other way to do it?

Otherwise should I define one more array to store the initial latlng values then to check each time whether latlng is changed or not (in this scenario I can replace only updated latlng markers right?No need to replace all markers every time right?)


回答1:


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

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.

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);


来源:https://stackoverflow.com/questions/48900378/how-to-update-leaflet-markers-for-every-5-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!