I'm trying to find a point on a line closest to a third point off of the line. The points are latitude/longitude.
The simple graphic shows what I'm trying to achieve. I'm using it for javascript, but any language or formula would still work. I know this is basic geometry, but I'm still having trouble finding a formula on google :S lol... stay in school!
var a = '48,-90';
var b = '49,-92';
var c = '48.25,-91.8';
var d = 'calculated point on line';
RCrowe @ Find a point in a polyline which is closest to a latlng
Let A,B,C be double[] such that A = {x,y} of a, B = {x,y} of b, and C = {x,y} of c. If the line ab is y = mx + z, then
m = (A[1]-B[1])/(A[0]-B[0])
z = A[1] - m*A[0]
Now we need the line through c perpendicular to ab. If this line is y = m'x + z', then
m' = -1/m = (A[0]-B[0])/(B[1]-A[1])
z' = C[1] - m'*C[0]
Finally we need the intersection of these lines. We set y=y and solve
mx+z = m'x + z'
x(m-m') = z'-z
x = (z'-z)/(m-m')
y = m*x + z
D = {(z'-z)/(m-m'), m*x + z}. All that remains now is the trivial conversion to String. Hope it helps!
The closest point on a line to a point can usually be determined by drawing a perpendicular line intersecting the point. To find the perpendicular slope, do the following code:
This is the slope formula (y2 - y1) / (x2 - x1)
Now that we have the slope, it is easy to convert to a perpendicular slope.
Now, we need to apply the point-slope formula (y - y1 = slope * (x - x1)).
Next, we have to get the slope intercept form of the first line.
I've created a system of equations here. To solve it, we'll have to use the transitive property (if a = b and b = c, then a = c);
I eliminated the y variables using the transitive property and conjoined the equations. Then I solved for x. I then plugged the x value in and solved for the y value. This is where the original line and the perpendicular line meet.
Remember how earlier I stated that this usually works?
Since you're using line segments not lines, sometimes the closest point will be the end points.
Here's how to fix the value of d
I used a formula called the distance formula (square root of (x1 - x2)^2 + (y1 - y2)^2) to determine the distance between the points. I then used shorthand if statements to determine the closest point.
If you need more help, just leave a comment.