[英]Deep cloning of feature attributes in OpenLayers
我需要克隆 OpenLayers 中的一個功能(我使用的是最新的 6.3.1 版本,但我猜我的問題不是特定於版本的)。
該功能本身有一個方法.clone()
。 不幸的是,我為特征定義的屬性/屬性是對象,arrays 和.clone
方法只對特征進行淺拷貝。 因此,如果我在克隆的 object 中更改某些值,則原始 object 也會更改。
那么,如何對 OpenLayers 中的某個功能進行深度復制呢?
正如Anatoly在評論中建議的那樣,它可以通過.setProperties()
方法來完成。
編輯 18.4.2020:由於該功能的幾何圖形包含在.getProperties()
中,並且無法使用JSON.parse()
/ JSON.stringify()
正確復制,我不得不在原始代碼中再添加一行,設置geometry
clonedProperties
的屬性。
我的代碼(沒有任何外部庫)如下:
const clonedFeature = feature.clone();
const clonedProperties = JSON.parse(JSON.stringify(feature.getProperties()));
clonedProperties.geometry = clonedFeature.getGeometry(); // see EDIT
// Maybe do something with clonedProperties as I do.
clonedFeature.setProperties(clonedProperties, true);
我在 ol@6.5.0 中遇到了同樣的問題。 在我的例子中,我使用feature.clone
方法來克隆一個動畫特征,當我改變克隆特征的比例、不透明度、旋轉屬性時,原點特征也發生了變化。
我 go 到 ol 的 github 問題找不到答案,我猜feature.clone
api 沒有深度克隆屬性。 於是我閱讀了ol的feature.clone
源碼,發現feature'style沒有clone,所以只需要重寫clone api,clone style就可以解決問題了。
/** * Clone this feature. If the original feature has a geometry it * is also cloned. The feature id is not set in the clone. * @return {Feature} The clone. * @api */ clone() { const clone = new Feature( this.hasProperties()? this.getProperties(): null ); clone.setGeometryName(this.getGeometryName()); const geometry = this.getGeometry(); if (geometry) { clone.setGeometry(geometry.clone()); } const style = this.getStyle(); if (style) { // clone.setStyle(style); // just setStyle the clone style clone.setStyle(style.clone()); } return clone; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.