Move feature from one location to another in OpenLayers 3
Asked Answered
O

2

5

How do I move a vector feature from one position on a map to another?

I have the following which generates an icon at (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);

This works fine, but how do I now move it to another location?

I've tried:

iconFeature.move(x,y);

I've also tried

iconFeature.geometry.move(x,y);

The latter says that iconFeature.geometry is undefined, the first says icon.move() is not a function.

Previous answers on SO suggest these solutions, but they don't seem to work for me.

Ohmage answered 31/10, 2014 at 18:10 Comment(0)
C
6

Actually you can do this using the new ol.coordinate.add method, see the docs.

I have added a jsFiddle demonstrating this, red points are the original, and the green ones are those points moved a random distance.

To get the points, use forEachFeature on the vector source, and getGeometry().getCoordinates() to get the actual coordinates, and the setGeometry, eg,

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);
    }
);

In this fiddle I created a new geometry rather than moving the existing one. Obviously, for something other than a point you would have to iterate through the coordinates array. To only move a specific geometry, there are is the getFeatureById method of ol.Feature that can be used to get a specific feature, whose geometry you can then move and update, as above.

Ceballos answered 1/11, 2014 at 10:47 Comment(4)
Thank you, a nice solution and great example to demonstrate it with. For a single point of interest OL3 overlays are also a solution using setPosition() to move them, this was my interim solution.Ohmage
You are welcome. I am starting to enjoy OL3, being a long time OL2 dev, after the initial shock factor of a total rewrite has worn off :DCeballos
jsfiddle is not valid anymore, it is pointing to a location where ol.js doesn't existEnuresis
@Icarus. Thanks, updated the fiddle with a cdn source.Ceballos
M
5

There's translate method for moving geometries:

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

NB, that's for relative moving. If you want to move your point to absolute position, you have to calculate distances between original and desired location.

Mong answered 4/11, 2015 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.