有效地将多个标记添加到矢量图层

Gia*_*o M 1 javascript openlayers

我需要在 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
    })
});
Run Code Online (Sandbox Code Playgroud)

要添加标记,我使用以下代码:

for (let i = 0; i < data.length; i++) {
    addressOSM.addLayer(createMarker(data[i].longitude, data[i].latitude, data[i].id)));
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

这段代码可以工作,但速度相当慢。
我该如何改进它以提高效率?

Mik*_*ike 5

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

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
    });
}
Run Code Online (Sandbox Code Playgroud)