首页 > 解决方案 > 有效地将多个标记添加到矢量图层

问题描述

我需要在 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;
}

此代码有效,但速度很慢。
如何改进它以提高效率?

标签: javascriptopenlayers

解决方案


您不需要为每个功能创建一个新图层,它们都可以放在一个图层中

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
    });
}

推荐阅读