I'm animating a marker along a route with waypoints and I am trying to detect when the marker reaches/ crosses a waypoint.
I've managed to get the animation part but seems to fail on the detections
here is my code
I'm creating the route
p = data.map(function(o){ return o.steps.map(function(g) { return g.geometry.coordinates }) });
const locations = p.reduce(function(arr, val){
arr = arr.concat(val); return arr ;
}, [] ),
route = new MultiLineString(locations);
I get the waypoints
intersections = data.reduce(function(s,c){ s=(!s?[]:s); return s = s.concat(c.steps.reduce(
function(e,a){
e = (!e? [] : e);
e.push(a.maneuver.location);
return e; },[])); return s;
},[]),
I create an extent from the waypoint on "right arrow click"
waypoint = fromLonLat(intersections[0])
.concat(fromLonLat(intersections[1]));
Then trying to detect when the marker is animated pass the waypoint
function moveFeature(event) {
const speed = 60;
const time = event.frameState.time;
const elapsedTime = time - lastTime;
distance = (distance + (speed * elapsedTime) / 1e6) % 2;
lastTime = time;
const currentCoordinate = route.getLineString(distance).getCoordinateAt(distance);
if(isNaN(currentCoordinate[0]) || (distance > 1) || Extent.containsCoordinate(waypoint, currentCoordinate) ) return stopAnimation();
position.setCoordinates(currentCoordinate);
const vectorContext = getVectorContext(event);
vectorContext.setStyle(styles.geoMarker);
vectorContext.drawGeometry(position);
map.getView().setCenter(currentCoordinate);
map.render();
}
But it doesn't seem to be true. Is there another way I can detect when the marker is past a certain point/ radius ?
Unless movefeature
stops exactly on the extent Extent.containsCoordinate
will not return true and the animation will continue past the point. It would be better to calculate the distance (or fraction of total distance) to the waypoint and stop when that is reached
const nearest = route.getClosestPoint(waypoint);
const partCoordinates = [];
route.forEachSegment(function(start, end){
partCoordinates.push(start.slice());
if (new LineString([start, end]).intersectsCoordinate(nearest)) {
partCoordinates.push(nearest);
return true;
}
});
const fraction = new LineString(partCoordinates).getLength() / route.getLength();