I have a Linestring feature as my route on the openlayers map. I use Modify class to make changes on the route. After every time that I modify this line I need to get the coordinates of the point which has been moved. (Ideally coordinates of the point before and after the modification.)
why do I need it: I need to add waypoints to my route. so after every modification I need to store the coordinates of the modified points of the line as my waypoints and send them to my routing API.
I use openlayers version 6.9.0
Take a copy of the coordinates at the modifystart
event, take another at the modifyend
event. Then find the coordinate which has been added, removed or changed:
let oldCoordinates;
modify.on('modifystart', (e) => {
oldCoordinates = e.features
.item(0)
.getGeometry()
.clone()
.getCoordinates();
});
modify.on('modifyend', (e) => {
const newCoordinates = e.features
.item(0)
.getGeometry()
.clone()
.getCoordinates();
if (newCoordinates.length < oldCoordinates.length) {
const removed = oldCoordinates.find(
(coordinate, index) =>
coordinate[0] !== newCoordinates[index][0] &&
coordinate[1] !== newCoordinates[index][1]
);
console.log('removed', removed);
} else if (newCoordinates.length > oldCoordinates.length) {
const added = newCoordinates.find(
(coordinate, index) =>
coordinate[0] !== oldCoordinates[index][0] &&
coordinate[1] !== oldCoordinates[index][1]
);
console.log('added', added);
} else {
let changedFrom;
const changedTo = newCoordinates.find((coordinate, index) => {
changedFrom = oldCoordinates[index];
return (
coordinate[0] !== changedFrom[0] && coordinate[1] !== changedFrom[1]
);
});
console.log('changed from', changedFrom, 'to', changedTo);
}