I have a point and a path, polyline, or set of points to create lines.
How can I find the point on my path which closest to another disconnected point?
It\'
Here is the algorithm that I've implemented as a solution. There's nothing 'non-obvious' in here if you've spent more than ten minutes thinking about it.
I'll reference the distance algorithm which you can find here: https://stackoverflow.com/a/1501725/146077
The answer linked above uses a projection to test if the point is closest to either end of the interval than any other point. I've modified the function from that answer to return the point's position on that projection. Beware that this answer might not make any sense if you haven't read the linked answer!
private Point GetClosestPointOnLine(Point start, Point end, Point p)
{
var length = (start - end).LengthSquared;
if (length == 0.0)
return start;
// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2
var t = (p - start) * (end - start) / length;
if (t < 0.0)
return start; // Beyond the 'v' end of the segment
else if (t > 1.0)
return end; // Beyond the 'w' end of the segment
// Projection falls on the segment
var projection = start + t * (end - start);
return projection;
}