Single Entity
Single Entity

Reputation: 3115

Move feature from one location to another in OpenLayers 3

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.

Upvotes: 5

Views: 15785

Answers (2)

John Powell
John Powell

Reputation: 12571

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.

Upvotes: 6

user1702401
user1702401

Reputation: 1658

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.

Upvotes: 5

Related Questions