I need a basic function to find the shortest distance between a point and a line segment. Feel free to write the solution in any language you want; I can translate it into what I'm using (Javascript).
EDIT: My line segment is defined by two endpoints. So my line segment AB
is defined by the two points A (x1,y1)
and B (x2,y2)
. I'm trying to find the distance between this line segment and a point C (x3,y3)
. My geometry skills are rusty, so the examples I've seen are confusing, I'm sorry to admit.
For anyone interested, here's a trivial conversion of Joshua's Javascript code to Objective-C:
I needed this solution to work with
MKMapPoint
so I will share it in case someone else needs it. Just some minor change and this will return the distance in meters :Here is devnullicus's C++ version converted to C#. For my implementation I needed to know the point of intersection and found his solution to work well.
Here is same thing as the C++ answer but ported to pascal. The order of the point parameter has changed to suit my code but is the same thing.
Consider this modification to Grumdrig's answer above. Many times you'll find that floating point imprecision can cause problems. I'm using doubles in the version below, but you can easily change to floats. The important part is that it uses an epsilon to handle the "slop". In addition, you'll many times want to know WHERE the intersection happened, or if it happened at all. If the returned t is < 0.0 or > 1.0, no collision occurred. However, even if no collision occurred, many times you'll want to know where the closest point on the segment to P is, and thus I use qx and qy to return this location.
WPF version:
C#
Adapted from @Grumdrig