2014-03-17

Calculate the distance between two geo locations

We are developing a location based app and we encounter a problem about the geo location yesterday. Which is "how to get the distance between two points in the map". It seem to be easy if using our usual XY coordination system (the Cartesian coordinate). However, the inputs are the latitude and longitude, not the unit of meter;



Formula:

acos( 
   cos(a.lat) x cos(a.long) x cos(b.lat) x cos(b.long) 
   + cos(a.lat) x sin(a.long) x  cos(b.lat) x sin(b.long)
   + sin(a.lat)*sin(b.lat)
)  x  earth.radius

Where:

a.lat, a.long  = latitude and longitude of the 1st point ( in radians)
b.lat, b.long  = latitude and longitude of the 2nd point ( in radians)
earth.radius = the radius of the earth;  (which is: 3443.9 nautical miles or 6378 km)


Source Code (in java):


public static double distanceBetween(double lat1, double long1, double lat2, double long2)
{
 double rLat1 = Math.toRadians(lat1);
 double rLong1 = Math.toRadians(long1);
 double rLat2 = Math.toRadians(lat2);
 double rLong2 = Math.toRadians(long2);
  
 double part1 = Math.cos(rLat1) * Math.cos(rLong1) * Math.cos(rLat2) * Math.cos(rLong2);
 double part2 = Math.cos(rLat1) * Math.sin(rLong1) * Math.cos(rLat2) * Math.sin(rLong2);
 double part3 = Math.sin(rLat1) * Math.sin(rLat2);
 
 return Math.acos(part1 + part2 + part3) * RADIUS;
}

Reference: 

There are more documentation talking about the distance calculation, also google provide API to do so.