javascript - 有效地将多个标记添加到矢量图层
问题描述
我需要在 openlayer 地图上添加多个(如 20 个)标记。
现在我能够做到这一点,但我确信这不是更有效的方法。
这是我在网上找到的代码:
var addressOSM = new ol.Map({
controls: null,
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([lng, lat]),
zoom: 15
})
});
要添加标记,我使用以下代码:
for (let i = 0; i < data.length; i++) {
addressOSM.addLayer(createMarker(data[i].longitude, data[i].latitude, data[i].id)));
}
createMarker
功能是:
function createMarker(lng, lat, id) {
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(lng), parseFloat(lat)])),
id: id
})]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "url_to_png.png"
})
})
});
return vectorLayer;
}
此代码有效,但速度很慢。
如何改进它以提高效率?
解决方案
您不需要为每个功能创建一个新图层,它们都可以放在一个图层中
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "url_to_png.png"
})
})
});
addressOSM.addLayer(vectorLayer);
for (let i = 0; i < data.length; i++) {
vectorLayer.getSource().addFeature(createMarker(data[i].longitude, data[i].latitude, data[i].id)));
}
function createMarker(lng, lat, id) {
return new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([parseFloat(lng), parseFloat(lat)])),
id: id
});
}
推荐阅读
- python - 如何在没有列洗牌的情况下从 Dask Dataframe 制作新的 pandas Dataframe?
- python - 如何在python中检查程序的运行时间
- tabs - Puppeteer 关闭新标签
- php - 在 PDF Laravel 中获取错误未定义偏移量 -1
- django - 带有 Case 的 Django QuerySet 注释似乎是误报
- javascript - 在我检查之前无法获取网站的元素名称
- javascript - 防止2个连续数字正则表达式
- python - Jupyter Notebook:文件路径或缓冲区对象类型无效:
Python - react-native - 反应原生选择多个项目,如画廊
- python - 从 Python 中的 SOAP 响应中提取 XML 数据