Saturday, July 12, 2008

Distance Calculation between Two Points with given Longitude and Latitude (java code)

This is done by Haversine formula. The formula is like ,

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

R=radius of Earth

The implementation of this function with JAVA is given below,

//Haversine Formula
double DistLatLong(double lat1, double lon1, double lat2, double lon2, char units) {

double dlon, dlat;
dlon = lon2 - lon1;
dlat = lat2 - lat1;
double a = (Math.sin(dlat/2))*(Math.sin(dlat/2)) + Math.cos(lat1) * Math.cos(lat2) * (Math.sin(dlon/2))*(Math.sin(dlon/2));
double c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a) );
double R=0;
// R (Earth Radius) = 3956.0 mi = 3437.7 nm = 6367.0 km
switch(units)
{
case 'S': // STATUTE MILES
R = 3956.0;
break;
case 'N': // NAUTICAL
R = 3437.7;
break;
case 'K': // KILOMETERS
R = 6367.0;
break;
}
return (R * c);
}

No comments:

search engine

Custom Search