Issue I'm facing
The current method for finding the closest waypoint may not accurately determine the true nearest waypoint when the selected point is near the intersection of multiple lines. This is because the function relies solely on the distance between the clicked point and the waypoints' coordinates, without considering the lineStrings associated with each waypoint.
I'm open to suggestions for alternative approaches, such as using a spatial index or a different algorithm.
My current approach for finding the closest waypoint to a clicked point
I'm using Turf.js to draw lineStrings between specific points. I have an array of waypoints and I'm currently searching for the closest waypoint to a clicked point by comparing the clicked coordinates to the coordinates of each waypoint. I'm converting the clicked coordinates to a point on the lineString using the turf.pointOnLine()
function and then finding the closest waypoint using the findClosestWaypoint()
function.
Searching for the closest waypoint
const findClosestWaypoint = (clickedCoordinates) => {
let closestWaypoint = null;
let minDistance = Infinity;
waypoints.forEach((waypoint) => {
const distance = turf.distance(
turf.point([waypoint.longitude, waypoint.latitude]),
turf.point(clickedCoordinates)
);
if (distance < minDistance) {
minDistance = distance;
closestWaypoint = waypoint;
}
});
return closestWaypoint;
};
Usage of the closest waypoint later
const clickedLineStringPoint = turf.pointOnLine(lineStrings, [coordinates.lng, coordinates.lat]);
const clickedCoordinates = clickedLineStringPoint.geometry.coordinates;
const closestWaypoint = findClosestWaypoint(clickedCoordinates);