Sunday, December 20, 2009

Calculating distances between two latitude-longitude points

Well, today I decided to make a little program for my mobile phone and I have to calculate the distance between two points (latitude, longitude) ... How can I do?

Haversine formula
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. These names follow from the fact that they are customarily written in terms of the haversine function, given by haversin(θ) = sin^2(θ/2).

For any two points p1=(lat1,long1), p2=(lat2,long2) on a sphere (like earth)
haversin(d/R) = haversin(lat1-lat2) + cos(lat1)cos(lat2)haversin(long2-long1)

where
R = earth’s radius (6,371km)
d = distance between the two points along a great circle of the sphere.

Now we can calculate our "d" doing:
R = 6371km
Δlat = lat2− lat1
Δlong = long2− long1
a = sin^2(Δlat/2) + cos(lat1).cos(lat2).sin^2(Δlong/2)
c = 2*atan2(sqrt(a), sqrt(1−a))
d = R*c

The Haversine formula is useful for numerical calculation even at small distance, but if it isn't necessary to use such precision we can use the spherical law of cosines.
d = R * acos(sin(lat1).sin(lat2)+cos(lat1).cos(lat2).cos(long2−long1))

easier and faster to calculate.

For example:

var R = 6371;
var d = R * Math.acos(Math.sin(lat1)*Math.sin(lat2) +
Math.cos(lat1)*Math.cos(lat2) *
Math.cos(lon2-lon1));

No comments:

Post a Comment