Closest line to a point

2008-10-27

Too much time was spent on this crap.
Here's an algorithm to compute the nearest line to a given point.

Anyways, use it, love it, copy it.
It's in Java but should be easily portable.

Code: (Java)
/**
* Compute the distance between point 3 and the line between point 1 and 2.
* Algorithm: http://ozviz.wasp.uwa.edu.au/~pbourke/geometry/pointline/
*/
double getDistance(int x1, int y1, int x2, int y2, int x3, int y3) {
int top = ((x3-x1)*(x2-x1)) + ((y3-y1)*(y2-y1));
int bottom = (int)(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
double u = (double)top / (double)bottom; // dont cast and die.
if (u < 0) {
// nearest vertex is x1, point is not straight on the line
// compute distance to it if you want, same way as below
// x4 = x1;
// y4 = y1;
return Double.POSITIVE_INFINITY;
}
else if (u > 1) {
// nearest vertex is x2, point is not straight on the line
// compute distance to it if you want, same way as below
// x4 = x2;
// y4 = y2;
return Double.POSITIVE_INFINITY;
}
else {
// p4 is the point on the line that makes a
// straight angle towards the given point
int x4 = (int)Math.round(x1 + (u * (x2 - x1)));
int y4 = (int)Math.round(y1 + (u * (y2 - y1)));
return Math.sqrt(Math.pow(x3 - x4, 2) + Math.pow(y3 - y4, 2));
}
}


To get the nearest line, simply loop through all the lines and get the lowest line, how hard can it be ;)