openlayers 刪除點 ol/source/Vector.js.VectorSource.removeFeature解決方案

背景:openlayers 實現地圖打點,根據數據的變化修改點的位置
在這裏插入圖片描述

data

// 點的經緯度
coordinates: [
// { x: 37.12638163, y: 15.1353712537 },
// { x: 82.56253054272383, y: 42.63299560546875 },
// { x: 87.52801179885864, y: 44.15955126285553 }
]

methods

/**
* 批量添加座標點
*/
handleAddBatchFeature() {
 const _that = this;
 // 設置圖層
 _that.flagLayer = new VectorLayer({
   source: new VectorSource()
 });
 _that.map.addLayer(_that.flagLayer);
 // 循環添加feature
 for (let i = 0; i < this.coordinates.length; i++) {
   // 創建feature
   let feature = new Feature({
     geometry: new Point([_that.coordinates[i].x, _that.coordinates[i].y])
   });
   // 設置ID
   feature.setId(i + "xx");
   feature.setStyle(_that.getIcon());
   _that.features.push(feature);
 } // for 結束
 // 批量添加feature
 _that.flagLayer.getSource().addFeatures(_that.features);
},

上面就可以實現批量打點操作。我修改 data 的數據,希望實現點的實時更新操作

刪除點,需要先從Feature裏移除icon,然後再移除圖層,如果不從Feature裏移除icon而直接移除圖層,則同一個實例化方法中icon一直存在,只是由於圖層不存在而未在地圖上顯示出來。

刪除點,刪除圖層代碼

this.flagLayer.getSource().removeFeature(this.features); //先默認移除icon的feature
this.map.removeLayer(this.flagLayer); //在移除圖層

感覺上面的邏輯符合,但是往往會事與願違!!!

下面我操作coordinates數據我刪除了一個點,但是頁面點的位置並沒有消失,就是說移除點是錯誤的。
在這裏插入圖片描述
報錯信息:VectorSource../node_modules/[email protected]@ol/source/Vector.js.VectorSource.removeFeature

默認說forEach of undefined 但是上面數據顯示數組存在兩個值。
在這裏插入圖片描述
經過N小時的摸索,終於找到了解決辦法。

let _that = this;
this.flagLayer
  .getSource()
  .getFeatures()
  .forEach(function(feature) {
    _that.flagLayer.getSource().removeFeature(feature);
  });
this.features = [];?
console.log(this.features);
// this.flagLayer.getSource().removeFeature(this.features); //錯誤寫法
this.map.removeLayer(this.flagLayer);

感謝參考博文:https://blog.csdn.net/ZillahV06/article/details/80449044

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章