在OpenLayers 3中将功能从一个位置移动到另一个位置

Sin*_*ity 4 javascript 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);
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我现在如何将其移动到另一个位置?

我试过了:

iconFeature.move(x,y);
Run Code Online (Sandbox Code Playgroud)

我也试过了

iconFeature.geometry.move(x,y);
Run Code Online (Sandbox Code Playgroud)

后者说iconFeature.geometry未定义,第一个说icon.move()不是函数.

关于SO的先前答案提出了这些解决方案,但它们似乎对我不起作用.

Joh*_*ell 5

实际上您可以使用新ol.coordinate.add方法执行此操作,请参阅文档.

我添加了一个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);
    }
);
Run Code Online (Sandbox Code Playgroud)

在这个小提琴中,我创建了一个新的几何体,而不是移动现有的几何体.显然,对于除点之外的其他东西,您必须遍历坐标数组.要仅移动特定几何体,可以使用getFeatureByIdol.Feature方法获取特定特征,然后可以移动和更新其几何,如上所述.


use*_*401 5

有一种translate移动几何图形的方法:

iconFeature.getGeometry().translate(deltaX, deltaY);
Run Code Online (Sandbox Code Playgroud)

注意,这是相对移动。如果要将点移动到绝对位置,则必须计算原始位置和所需位置之间的距离。