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.
Here is a more complete spelling out of Grumdrig's solution. This version also returns the closest point itself.
see the Matlab GEOMETRY toolbox in the following website: http://people.sc.fsu.edu/~jburkardt/m_src/geometry/geometry.html
ctrl+f and type "segment" to find line segment related functions. the functions "segment_point_dist_2d.m" and "segment_point_dist_3d.m" are what you need.
The GEOMETRY codes are available in a C version and a C++ version and a FORTRAN77 version and a FORTRAN90 version and a MATLAB version.
In F#, the distance from the point
c
to the line segment betweena
andb
is given by:The vector
d
points froma
tob
along the line segment. The dot product ofd/s
withc-a
gives the parameter of the point of closest approach between the infinite line and the pointc
. Themin
andmax
function are used to clamp this parameter to the range0..s
so that the point lies betweena
andb
. Finally, the length ofa+p-c
is the distance fromc
to the closest point on the line segment.Example use:
Here's the code I ended up writing. This code assumes that a point is defined in the form of
{x:5, y:7}
. Note that this is not the absolute most efficient way, but it's the simplest and easiest-to-understand code that I could come up with.In my own question thread how to calculate shortest 2D distance between a point and a line segment in all cases in C, C# / .NET 2.0 or Java? I was asked to put a C# answer here when I find one: so here it is, modified from http://www.topcoder.com/tc?d1=tutorials&d2=geometry1&module=Static :
I'm @SO not to answer but ask questions so I hope I don't get million down votes for some reasons but constructing critic. I just wanted (and was encouraged) to share somebody else's ideas since the solutions in this thread are either with some exotic language (Fortran, Mathematica) or tagged as faulty by somebody. The only useful one (by Grumdrig) for me is written with C++ and nobody tagged it faulty. But it's missing the methods (dot etc.) that are called.
In Mathematica
It uses a parametric description of the segment, and projects the point into the line defined by the segment. As the parameter goes from 0 to 1 in the segment, if the projection is outside this bounds, we compute the distance to the corresponding enpoint, instead of the straight line normal to the segment.
Plotting result:
Plot those points nearer than a cutoff distance:
Contour Plot: