Showing posts with label match Library. Show all posts
Showing posts with label match Library. Show all posts

Thursday, April 4, 2013

Calculate Haversine Distance in Java


The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical triangle

The hav­er­sine formula is used to cal­cu­late the dis­tance between two points on the Earth’s surface spe­cified in lon­gitude and latitude. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".




d is the dis­tance between two points with lon­gitude and lat­itude (ψ,φ) and r is the radius of the Earth.

public class HaversineDistance {

public static double haversineDistance(double lat1,double lat2,double lon1,double lon2) {
           double deltaLat = Math.toRadians(lat1 - lat2);
           double deltaLong = Math.toRadians(lon1 - lon2);
           double lat1R = Math.toRadians(lat1);
           double lat2R = Math.toRadians(lat2);
           double a = (Math.sin(deltaLat/2.0) * Math.sin(deltaLat/2.0)) +
                      (Math.sin(deltaLong/2.0) * Math.sin(deltaLong/2.0) *
                      Math.cos(lat1R) * Math.cos(lat2R));
           double c = 2.0*Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
           double d = 3959.0*c;
           return d;
         }

         public static void main(String[] args) {
           System.out.println(haversineDistance(21.7679,40.4230,78.8718,98.7372));
         }

}