Computing distances with Lat/Lon


Have you ever wanted to compute distances with latitude and longitude? At first it seems so simple. We all learned the pythagorean theorem in elementary school:
d=sqrt((x2 – x1)^2 + (y2 – y1)^2)
So if we have our two points (x1,y1) and (x2,y2) then we should be able to find (x2-x1,y2-y1) and find the distance using the Pythagorean theorem, right? Well, no.

The Pythagorean theorem finds the straight line distance between two points. However, for two points any appreciable distance from each other on earth, trying to get to your destination would involve a lot of digging. Assuming you want to travel overland, you must travel further than the linear distance to account for the curvature of the Earth.

A little further research yields the Haversine Formula which is useful for computing surface distances on a sphere and correctly accounts for points that are very close together:

Haversine Formula (from R.W. Sinnott, “Virtues of the Haversine”, Sky and Telescope, vol. 68, no. 2, 1984, p. 159):

dlon = lon2 – lon1
dlat = lat2 – lat1
a = sin2(dlat/2) + cos(lat1) * cos(lat2) * sin2(dlon/2)
c = 2 * arcsin(min(1,sqrt(a)))
d = R * c

But what is R, the radius of the Earth?

It turns out the Earth is not a sphere after all. The spinning motion compresses the planet so that the equitorial radius is considerably larger than the polar radius. The shape of the Earth is well approximated by an oblate spheroid with a polar radius of 6357 km and an equatorial radius of 6378 km.

R’ = a * (1 – e2) / (1 – e2 * sin2(lat))^(3/2)

where a is the equatorial radius, b is the polar radius, and
e is the eccentricity of the ellipsoid = (1 – b2/a2)^(1/2).

Wow! So there you have it.

Of course if you’re trying to compute these values in client side javascript, it may take a while. It turns out that for short-ish distances at latitutudes within the continental United States, just pretending the Earth is a sphere yields errors of roughly 20 meters. That’s good enough for me..

(All from Google and http://www.faqs.org/faqs/geography/infosystems-faq/ )