2014-10-31 562 views
4

如何將矢量要素從地圖上的一個位置移動到另一個位置?在OpenLayers中將功能從一個位置移動到另一個位置3

我有一個在(0.0,0.0)生成一個圖標如下:

var iconFeature = new ol.Feature({ 
    geometry: new ol.geom.Point([0.0,0.0]) 
}); 

var iconStyle = new ol.style.Style({ 
    image: new ol.style.Icon(({ 
    anchor: [0.5, 46], 
    anchorXUnits: 'fraction', 
    anchorYUnits: 'pixels', 
    opacity: 0.75, 
    src: 'marker-icon.png' 
    })) 
}); 

iconFeature.setStyle(iconStyle); 

這工作得很好,但我怎麼現在它移動到另一個位置?

我已經試過:

iconFeature.move(x,y); 

我也試過

iconFeature.geometry.move(x,y); 

後者說iconFeature.geometry是不確定的,第一個說icon.move()不是一個函數。

先前在SO上的答案暗示了這些解決方案,但它們似乎並不適合我。

+0

解決方案發布,它可以完成,只是沒有很多文件。 – 2014-11-01 10:48:40

回答

5

其實你可以做到這一點使用新ol.coordinate.add方法,請參閱the docs.

我添加了一個jsFiddle證明這一點,紅點是原來的,綠色的是那些點移動的隨機距離。

要獲得積分,向量源上使用forEachFeature,並且getGeometry().getCoordinates()獲得實際的座標,setGeometry,例如,

vectorSource.forEachFeature(function(feature){ 
    var coordinate = feature.getGeometry().getCoordinates(); 
    //move coordinates some distance 
    ol.coordinate.add(coordinate, 10, 10); 
    //use setGeometry to move it 
    feature.setGeometry(new ol.coordinate); 
    } 
); 

在這撥弄我創建了一個新的幾何形狀,而不是把現有的一。顯然,除了點之外,你必須遍歷座標數組。要移動特定的幾何圖形,可以使用getFeatureById method of ol.Feature來獲取特定的特徵,然後可以移動和更新其幾何圖形,如上所述。

+0

謝謝你,一個很好的解決方案和很好的例子來證明它。對於單個興趣點而言,OL3疊加層也是使用setPosition()來移動它們的解決方案,這是我的臨時解決方案。 – 2014-11-01 10:59:11

+1

不客氣。我開始享受OL3,作爲一個很長時間的OL2開發,在整個重寫的最初震動因素已經磨損後:D – 2014-11-01 22:28:11

+0

jsfiddle無效,它指向ol.js不存在的位置 – Icarus 2017-08-23 09:20:14

2

translate方法用於移動幾何:

iconFeature.getGeometry().translate(deltaX, deltaY); 

NB,這對相對運動。如果您想將點移動到絕對位置,則必須計算原始位置和所需位置之間的距離。

相關問題