我正在制作传单 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/