I'm working on an open source program that involves drawing and it would be helpful to see which line is closest to the user's selection. I have a point specified by coordinates and a line specified by its start and end coordinates and I want to calculate the closest the point comes to the line.

According to Wikipedia there's an equation I can use: http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line

$$ \operatorname{distance}(P_1, P_2, (x_0, y_0)) = \frac{|(y_2-y_1)x_0-(x_2-x_1)y_0+x_2 y_1-y_2 x_1|}{\sqrt{(y_2-y_1)^2+(x_2-x_1)^2}}. $$

...however, I get seemingly odd results from applying this equation. Example:

Point (3.2, -4.35)

Line A (29.07, -30.04) to (29.78, -30.34)

Line B (29.78, -30.34) to (30.68, -30.25)

Applying the equation, I get a distance of 13.60 from line A and 28.51 from line B. This seems completely wrong given that the two lines are very short and very close! Is my calculation wrong (I've checked it a lot!) or am I using the wrong equation?

  • $\begingroup$ Actually, I think I've figured it out... according to the equation, the line just goes through those points, not stops at those points, right? So small changes in the co-ordinates can make significant changes to the angle of the line and the distance of the point from the line. $\endgroup$
    – Rich Smith
    Jan 16, 2015 at 19:12
  • 1
    $\begingroup$ Yes, that's exactly right. A line has infinite breadth and the distance from a point to a line is the distance from that point to the closest point on the line. That would be a lot different than the closes point on a line segment. $\endgroup$ Jan 16, 2015 at 19:13
  • $\begingroup$ Thanks Matthew, I've clearly not been searching with the right terminology. I'd +1 your comment but I seem to be too new! $\endgroup$
    – Rich Smith
    Jan 16, 2015 at 19:42

1 Answer 1


They have extended the line segments to full lines.
You have short line segments, but their slopes are very different.
The first line slopes down, so when you extend back, it gets nearer the point.
The second line slopes up, so when you extend back, it gets further from the point.
One solution is to check whether the 'nearest point' is within the line segment, and if not, give the nearer endpoint.
Check whether $(x_0-x_1)(x_1-x_2)+(y_0-y_1)(y_1-y_2)$ and $(x_0-x_2)(x_1-x_2)+(y_0-y_2)(y_1-y_2)$ have the same sign (are both positive or both negative). If they do, then the nearest point lies outside the line segment. If they are opposite signs, then the nearest point lies on the line segment.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .