Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 759
Single Entity Avatar asked Dec 25 '22 02:12

Single Entity


1 Answers

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.

like image 82
John Powell Avatar answered Feb 19 '23 22:02

John Powell