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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With