Leaflet markerCluster定时无刷新更新数据时图层叠加问题
问题原因
每次定时器触发时都会新建markerClusterGroup图层直接添加到地图,未移除旧聚合图层,导致新旧数据叠加显示。
基础修复方案
将聚合图层变量声明放到定时器外层作用域,每次拉取新GeoJSON数据前,先移除已存在的旧图层,再加载新数据生成新聚合图层添加到地图。
修复后完整代码:
// 外层作用域声明变量,存储聚合图层引用 let clusters = null; setInterval(function() { $.getJSON("gdf1000_rand_tallinn_auto_try.geojson", function(data) { // 已存在旧图层则先移除 if (clusters) { map.removeLayer(clusters); } const tallinn_data = L.geoJson(data, { pointToLayer: function(feature, latlng) { const marker = L.marker(latlng); marker.bindPopup(feature.properties.lat); return marker; } }); clusters = L.markerClusterGroup(); clusters.addLayer(tallinn_data); map.addLayer(clusters); }); }, 60000);
优化方案
不需要反复创建销毁聚合图层实例,初始化时就把聚合图层加到地图,每次更新只需要调用clearLayers()清空图层内旧标记、添加新数据即可,能避免图层闪烁,性能更优:
// 初始化时直接创建聚合图层并添加到地图 const clusters = L.markerClusterGroup().addTo(map); setInterval(function() { $.getJSON("gdf1000_rand_tallinn_auto_try.geojson", function(data) { // 清空聚合组内所有旧标记 clusters.clearLayers(); const tallinn_data = L.geoJson(data, { pointToLayer: function(feature, latlng) { const marker = L.marker(latlng); marker.bindPopup(feature.properties.lat); return marker; } }); clusters.addLayer(tallinn_data); }); }, 60000);
内容的提问来源于stack exchange,提问作者Sourav Karmakar
相关产品推荐
相关产品推荐

