# Nearest point on the line or its extension from a point

What is easiest way to find the a point on a line (a1, b1), (a2, b2) or the extension of the line, which is nearest to a point (x1, y1).

-
Find the point $p$ such that the vector formed between $p$ and $(x_1,y_1)$ is orthogonal to the line. –  Brandon Carter Dec 26 '11 at 6:33
See this old thread for a worked example, which shouldn't be too hard to generalize. –  Dylan Moreland Dec 26 '11 at 6:47

At the nearest point, the angle that the line between $x_1x_2$ and $(?_1,?_2)$ makes with the line through $a_1b_1$ is 90. So its gradient is $\frac{-1}{g}$ if g is the gradient of the given line. Now make this line go through $(x_1,x_2)$ and find the intersection with the line through $(a_1,b_1)$.
The points on the line containing $(a_1,b_1),(a_2,b_2)$ are given by $(a_1,b_1) + t<a_2-a_1,b_2-b_1>$ for $t\in\mathbb{R}$. In case you aren't familiar with vectors, I use the notation $<x,y>$ to indicate a vector, which is something that can be added to a point $(a,b)$ to get a new point $(a+x,b+y)$, and can be multiplied by a real number $t$ to get a new vector $<tx,ty>$. You want to find the point closest to another point $(x,y)$. This turns out to be the point $$(a_1,b_1) + t<a_2-a_1,b_2-b_1> = ((1-t)a_1+ta_2,(1-t)b_1+tb_2)$$ such that the vector $<(1-t)a_1+ta_2-x,(1-t)b_1+tb_2-y>$ is perpendicular to the vector $<a_2-a_1,b_2-b_1>$. Two vectors are perpendicular if their dot product is zero, meaning $$<(1-t)a_1+ta_2-x,(1-t)b_1+tb_2-y>.<a_2-a_1,b_2-b_1>$$ $$= ((1-t)a_1+ta_2-x)(a_2 - a_1) + ((1-t)b_1+tb_2-y)(b_2 - b_1) = 0$$ and solving this for $t$ and plugging that into $((1-t)a_1+ta_2,(1-t)b_1+tb_2)$ gives you the desired point.