# Relatively simple geometry with latitude/longitude coordinates

I'm trying to calculate a user's deviation from a route defined as a list of latitude/longitude points that make up the route. My proposed solution is to try and calculate the distance between the user's position and where they would be if they were exactly on the line between the nearest point and the second-nearest point. Here's a diagram I've made to demonstrate:

The points are as follows:

l is the location of the user

a is the nearest route vertex to the user

b is the second-nearest route vertex to the user

p is the point the user would be on if they were exactly on the line between a and b but had made the same amount of progress along the line as they currently have

x is the distance the user has deviated from the route

So essentially all I need to do is work out the latitude/longitude of p so I can work out x (or vice-versa). However, thinking back to A-level geometry I can't think of a method that could give me those values. I've decided that the points are close enough together that I can use the euclidean distance between points rather than the haversine distance, to simplify matters. Does anyone know of a formula I could use to calculate this?

-
What is the input? What are the assumptions? Is the angle at $p$ right (the picture is not clear)? – dtldarek May 21 '12 at 13:19

If a is $(a_1, a_2)$ and b is $(b_1, b_2)$, then equation of line joining them is $y = mx+c$ where m = $\frac{b_2-a_2}{b_1-a_1}$ and c = $a_2-m a_1$. Now if l is $(l_1, l_2)$ then the distance you want is $\frac{l_2 - m l_1 - c}{\sqrt{1 + m^2}}$. You don't actually need to compute coordinates of p.