问题描述
我有一个跟踪实时数据的传单地图,目前我每隔x秒正确更新一次位置,但是旧的标记并未被删除.我要删除所有标记并重新添加它们.我认为这也会影响页面的内存,因为每次值都会增加166
I have a leaflet map that tracks realtime data and i currently have it updating the positions correctly every x seconds, but the old markers are not being deleted. Im at the point that I will just remove all markers and re-add them. I think this is also impacting memory for the page, because the values increase by 166 every time
我必须忽略一些非常愚蠢的东西.
I have to be overlooking something really silly.
我的json是这样的:
My json is like:
{"_items": [{"uniqueID": "a123", "isMoving": false, "bearing": 231, "longitude": -xx.xxxxx, "latitude": xx.xxxxx}]}
这是添加标记的代码
var marker = new Array();
for(i=0;i<myjson._items.length;i++){
var LamMarker = new L.marker([myjson._items[i].latitude, myjson._items[i].longitude],{
icon: autotop
});
console.log(myjson._items[i].latitude)
marker.push(LamMarker);
map.addLayer(marker[i]);
}
}
我一直在尝试
if (map.hasLayer(marker)) {
for(i=0;i<marker.length;i++) {
map.removeLayer(marker[i])
}
}
在我的函数触发之前.
任何帮助都会很棒.
推荐答案
删除所有标记的一种非常简单的方法是使用中介图层组:与其将标记直接添加到地图中,不如将其添加到地图中,然后将标记添加到该组中.然后使用其 clearLayers()
方法删除其所有子标记:
An extremely simple way of deleting all your markers is to use an intermediary Layer Group: instead of adding your Markers directly to your map, add the group to the map, and your Markers into the group. Then remove all its child Markers with its clearLayers()
method:
var map = L.map("map").setView([48.86, 2.35], 11);
var layerGroup = L.layerGroup().addTo(map);
function refreshMarkers() {
layerGroup.clearLayers();
for (var i = 0; i < 10; i += 1) {
L.marker(getRandomLatLng()).addTo(layerGroup);
}
}
setInterval(refreshMarkers, 2000);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
function getRandomLatLng() {
return [
48.8 + 0.1 * Math.random(),
2.25 + 0.2 * Math.random()
];
}
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<div id="map" style="height: 180px"></div>
这篇关于删除传单实时标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!