删除Openlayers中的图层

问题描述

我通过在OpenLayers中添加图层来添加标记。 我在asp项目中使用它,并加载了地图,并且可以添加多个图标。 现在,我加载位置并通过该图标显示它们。 我的代码是这样的:

for (var i = 0; i < loc.length; i++) {
        LocationArray.push(loc[i]);
        iconFeature = new ol.Feature({
            geometry: new ol.geom.Point(ol.proj.fromLonLat(loc[i])),name: 'Null Island',population: 4000,rainfall: 500
        });
        iconFeatures.pop();
        debugger
        iconFeatures.push(iconFeature);
        vectorSource = new ol.source.Vector({
            features: iconFeatures //add an array of features
        });

        iconStyle = new ol.style.Style({
            image: new ol.style.Icon(({
                anchor: [0.5,100],anchorXUnits: 'fraction',anchorYUnits: 'pixels',opacity: 0.8,src: '/images/icon.png',}))
        });
        vectorLayer = new ol.layer.Vector({
            source: vectorSource,style: iconStyle
        });

        map.addLayer(vectorLayer);
    }

现在,我想在单击该层时将其删除。 我可以检测到它被单击的位置并做出响应,但是我不知道如何删除它。 我的代码是这样的:

map.on('click',function (evt) {
        var feature = map.forEachFeatureAtPixel(evt.pixel,function (feature) {
            return feature;
        });
        if (feature) {
            var coordinates = feature.getGeometry().getCoordinates();
            if (confirm("Do you want to delete?")) {
                
              // What should I code here?

            }
        } else {
          // .....
        }
  });

解决方法

forEachFeatureAtPixel回调也可以接收该图层,如果您保存起来很容易删除该图层:

map.on('click',function (evt) {
        var vectorLayer;
        var feature = map.forEachFeatureAtPixel(evt.pixel,function (feature,layer) {
            vectorLayer = layer;
            return feature;
        });
        if (feature) {
            var coordinates = feature.getGeometry().getCoordinates();
            if (confirm("Do you want to delete?")) {
                
              map.removeLayer(vectorLayer);

            }
        } else {
          // .....
        }
  });
,

如果要保留图层但要删除标记,可以使用clear()方法。

vectorLayer.getSource().clear();
,

感谢您的回复 我已经通过const digitGeneration = [...range(10)].map(e => e.toString()); // This is ['0','1','2','3','4','5','6','7','8','9'] 代码找到了它

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...