我正在尝试实时制作 map 可视化,我不断通过网络套接字获取新点。最初在 map 上绘制这些标记似乎很简单,但我不确定在 Mapbox 上更新图层的正确方法是什么。
到目前为止,每当我得到一个新点时,我都会删除旧图层,创建一个新图层,然后将其添加到 map 上。这种方法的问题是它很慢,并且对于大量点(> 5000)它开始滞后。
// remove layer
if (this.pointsLayer != null) {
map.removeLayer(this.pointsLayer);
}
// build geoJSON
var geoJSON = { "type": "FeatureCollection", "features": [] };
geoJSON["features"] = tweets.map(function(tweet) {
return this.getGeoPoint(tweet);
}.bind(this));
// add geoJSON to layer
this.pointsLayer = L.mapbox.featureLayer(geoJSON, {
pointToLayer: function(feature, latlon) {
return L.circleMarker(latlon, {
fillColor: '#AA5042',
fillOpacity: 0.7,
radius: 3,
stroke: false
});
}
}).addTo(map);
有更好的方法吗?
最佳答案
您可以通过传递 false
而不是真实数据来创建一个空的 GeoJSON 层:
//create empty layer
this.pointsLayer = L.mapbox.featureLayer(false, {
pointToLayer: function(feature, latlon) {
return L.circleMarker(latlon, {
fillColor: '#AA5042',
fillOpacity: 0.7,
radius: 3,
stroke: false
});
}
}).addTo(map);
然后使用 .addData
在新推文出现时更新它。类似于:
// build geoJSON
var geoJSON = { "type": "FeatureCollection", "features": [] };
geoJSON["features"] = /**whatever function you use to build a single tweet's geoJSON**/
// add geoJSON to layer
this.pointsLayer.addData(geoJSON);
对于一条推文,我想您可以只创建一个功能而不是功能集合,尽管我不知道额外的抽象层是否会对性能产生任何影响。
编辑:这是一个示例 fiddle ,显示 .addData 方法的工作情况:
http://jsfiddle.net/nathansnider/4mwrwo0t/
如果添加 10,000 个点,速度确实会明显变慢,而对于 15,000 个点,速度确实很慢,但我怀疑这与如何添加点关系不大,而与渲染如此多的 CircleMarkers 的需求有关。
如果您还没有这样做,您可能想尝试使用新的 Leaflet 1.0 beta ,它可以更快地重绘矢量图层,并且通常对大型数据集的响应速度更快。比较这个 15,000 点的示例 using Leaflet 0.7.5相同的代码 using Leaflet 1.0.0b2 。并非所有内容都是固定的(两者都需要很长时间才能打开弹出窗口),但尝试拖动 map 时的延迟时间差异非常显着。
关于leaflet - 更新 Leaflet/Mapbox 中的图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203758/