Finding distances between 2 coordinates
Filed Under (Programming) by edy on 02-04-2008
Tagged Under : coordinate, geomapping, latitude, longitude
Have you ever wondered how to calculate distance between 2 coordinates in map? It turns out that the calculation is not that simple. There is a formula called Haversine and this formula will give you the exact precision to the meter unit. So what is the formula?
Haversine Formula:
R = earth’s radius (mean radius = 6,371km)
?lat = lat2? lat1
?long = long2? long1
a = sin²(?lat/2) + cos(lat1).cos(lat2).sin²(?long/2)
c = 2.atan2(?a, ?(1?a))
d = R.c
(Note that angles need to be in radians to pass to trig functions).
Looks very complicated isn’t it? If you don’t need the exact distance up to meter unit precision, there is a lot simpler formula that you can use. It’s called Spherical Law of Cosines.
Spherical Law of Cosines:
d = acos(sin(lat1).sin(lat2)+cos(lat1).cos(lat2).cos(long2?long1)).R
Or even better, in MySQL it can be translated to:
SELECT id, place_name,
ROUND( SQRT( POW((69.1 * (#Val(arguments.latitude)# - latitude)), 2) + POW((53 * (#Val(arguments.longitude)# - longitude)), 2)), 1) AS distance
FROM places
ORDER BY distance ASC
I hope this is useful for those who are interested in geomapping.
