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.
This is an implementation made for FINITE LINE SEGMENTS, not infinite lines like most other functions here seem to be (that's why I made this).
Example is here.
Python:
AS3:
Java
These were made from this.
And now my solution as well...... (Javascript)
It is very fast because I try to avoid any Math.pow functions.
As you can see, at the end of the function I have the distance of the line.
code is from the lib http://www.draw2d.org/graphiti/jsdoc/#!/example
For the lazy, here's my Objective-C port of @Grumdrig's solution above:
coded in t-sql
the point is (@px, @py) and the line segment runs from (@ax, @ay) to (@bx, @by)
Looks like just about everyone else on StackOverflow has contributed an answer (23 answers so far), so here's my contribution for C#. This is mostly based on the answer by M. Katz, which in turn is based on the answer by Grumdrig.
And here's a little test program.
As you can see, I tried to measure the difference between using the version that avoids the Sqrt() method and the normal version. My tests indicate you can maybe save about 2.5%, but I'm not even sure of that - the variations within the various test runs were of the same order of magnitude. I also tried measuring the version posted by Matti (plus an obvious optimization), and that version seems to be about 4% slower than the version based on Katz/Grumdrig code.
Edit: Incidentally, I've also tried measuring a method that finds the distance to an infinite line (not a line segment) using a cross product (and a Sqrt()), and it's about 32% faster.
Grumdrig's C++/JavaScript implementation was very useful to me, so I have provided a Python direct port that I am using. The complete code is here.