Openlayers:删除图层后,不会将新图层添加到地图中

Openlayers: Once a layer is removed, new layers won't be added to the map

我是初学者,所以我可能忽略了一些非常明显的东西: 所以我有这个函数,我通过单击按钮调用它,以从地图中获取图层,如果它们是 dataLayer2 或 dataLayer3,则应将其删除,然后应将 dataLayer1 添加到地图中。我对其他 dataLayers 具有相同的功能,这些数据层是通过单击其他按钮调用的。如果图层是加载页面后第一个添加的图层,则图层将添加到地图中。如果您单击另一个应该删除活动层并添加新层的按钮,则旧层将从地图中删除,但不会添加新层。我没有从控制台收到任何错误或任何信息。所有层的数据都来自同一个文件。根据不同的属性,图层的样式只是不同的。几何形状保持不变。我尝试只加载图层,然后单击按钮重新设置样式,但这也没有用。就像我说的,我是初学者,可能会忽略这里的一些东西。

addDataLayer1(){

this.map.getLayers().forEach(layer => {
  if (layer === this.dataLayer2 || layer === this.dataLayer3){
    this.map.removeLayer(layer);
  }
})

this.dataLayer1 = new VectorImage({ 
  source: new VectorSource({
    overlaps:false,
    features: new TopoJSON().readFeatures(file)
  })
});
this.map.addLayer(this.dataLayer1);

从 Layers 容器中删除项目 对其进行迭代会破坏其完整性(正如 Mike 的评论所指出的)。

这是一个诱人的错误,因为它对 getLayers() 返回的 Container 对象不透明,在内部实现为数组。

Adding/Removing层数

如果图层不是地图的一部分,

removeLayer() 将无效。因此不需要遍历层集合和 'search' 来移除层。

addDataLayer1(){
    // simply remove the unwanted layers
    // this will have no effect if the layer to be removed is not part of the map
    this.map.removeLayer(this.dataLayer2);
    this.map.removeLayer(this.dataLayer3);

    // add the new layer to the map
    this.map.addLayer(this.dataLayer1);
}

上面的代码将在绘制顺序 ('z-index') 的末尾添加 this.dataLayer1this.dataLayer1 将绘制在所有现有图层之上 - 可能会过度绘制现有图层。

特征样式

在你的问题中你说

The data is all from the same file for all the layers. The styling is just different for the layers depending on different attributes.

使用不同的图层不是唯一(可能不是最好的)处理 VectorLayer 样式的解决方案。 相反,您可以在矢量图层的样式函数中使用要素属性 select/alter 样式:

// coordinates for the features
// projected from WGS84/EPSG:4326 to Web Mercartor/EPSG:3857
var newYorkCityCoordinates  = ol.proj.fromLonLat([-74.006111, 40.712778]);
var washingtonDCCoordinates = ol.proj.fromLonLat([-77.016389, 38.904722]);

// create a feature
var newYorkCityFeature = new ol.Feature({
    geometry: new ol.geom.Point(newYorkCityCoordinates)
});
// set the style property
newYorkCityFeature.set('circleColor', 'purple');

// create a feature with style property inline 
var washingtonDCFeature = new ol.Feature({
    geometry: new ol.geom.Point(washingtonDCCoordinates),
    circleColor: 'yellow' // this is our style property
});

// create the vector source with the two features
var vectorSource = new ol.source.Vector({
    features: [newYorkCityFeature, washingtonDCFeature]
});
// create vector layer with dynamic style function
var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  // the feature to be styled is passed to the style function
  style: function (feature, resolution) {
    return [new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: new ol.style.Fill({
            color: feature.get('circleColor') // use style attribute for the fill color
        })
      })
    })];
  }
});