Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a point is nearby a certain line?

I asked "How can I tell if a point belongs to a certain line?" before and I found a suitable answer so thank you very much.

Now, I would like to know how to tell if a certain point is close to my line.

like image 739
Wahid Bitar Avatar asked May 26 '09 14:05

Wahid Bitar


2 Answers

You need to calculate the right angle distance to the line. Then you have to define what "close" is and test if it is within that distance.

The equation you want is:

d=|v^^·r|=(|(x_2-x_1)(y_1-y_0)-(x_1-x_0)(y_2-y_1)|)/(sqrt((x_2-x_1)^2+(y_2-y_1)^2)).

like image 137
Alan Jackson Avatar answered Sep 29 '22 17:09

Alan Jackson


@Alan Jackson's answer is almost perfect - but his first (and most up-voted) comment suggests that endpoints are not correctly handled. To ensure the point is on the segment, simply create a box where the segment is a diagonal, then check if the point is contained within. Here is the pseudo-code:

Given Line ab, comprised of points a and b, and Point p, in question:

int buffer = 25;//this is the distance that you would still consider the point nearby
Point topLeft = new Point(minimum(a.x, b.x), minimum(a.y, b.y));
Point bottomRight = new Point(maximum(a.x, b.x), maximum(a.y, b.y));
Rect box = new Rect(topLeft.x - buffer, topLeft.y - buffer, bottomRight.x + buffer, bottomRight.y + buffer);
if (box.contains(p))
{
    //now run the test provided by Alan
    if (test)
        return true;
}
return false;
like image 45
Phil Avatar answered Sep 29 '22 17:09

Phil