首页 > 解决方案 > 如何从 OSM 中删除标记

问题描述

我正在做一个使用 Open Street Maps 的 Web 应用程序,我正在向它添加一些标记。我需要删除地图上的所有图层。

我已经尝试了一些我在其他问题上找到的例子,但没有一个对我有用。我不确定我是否使用开放层。

这是创建地图的代码:

function initialize_map() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    map = new ol.Map({
        target: "map",
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM({
                    url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
                })
            })
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([mapLng, mapLat]),
            zoom: mapDefaultZoom
        })
    });
    GetDados();
}

这是我用来添加标记的代码:

function add_map_point(lat, lng) {
    var vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
            })]
        }),
        style: new ol.style.Style({
            image: new ol.style.Icon({
                anchor: [0.5, 0.5],
                anchorXUnits: "fraction",
                anchorYUnits: "fraction",
                src: "https://www.freeiconspng.com/minicovers/bus-driver-icon-png-1.png"
            })
        })
    });
    map.addLayer(vectorLayer);
}

标签: javascripthtmlopenlayersopenstreetmap

解决方案


while (map.getLayers().removeAt(1)) {}

将从地图中删除除索引 0 之外的所有图层,这是您的 OSM 图层。

但是为什么每个标记都需要一个图层呢?如果在初始化地图时创建矢量图层,则只需添加点

function initialize_map() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    var vectorLayer = new ol.layer.Vector({
        source: new ol.source.Vector(),
        style: new ol.style.Style({
            image: new ol.style.Icon({
                anchor: [0.5, 0.5],
                anchorXUnits: "fraction",
                anchorYUnits: "fraction",
                src: "https://www.freeiconspng.com/minicovers/bus-driver-icon-png-1.png"
            })
        })
    });
    map = new ol.Map({
        target: "map",
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM({
                    url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
                })
            }),
            vectorLayer
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([mapLng, mapLat]),
            zoom: mapDefaultZoom
        })
    });
    GetDados();
}

function add_map_point(lat, lng) {
    vectorLayer.getSource().addFeature(
        new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
        })
    );
}

并且可以轻松清除它们

vectorLayer.getSource().clear();

推荐阅读