Monday, October 21, 2013

How to find distance b/w two points

You are normally using Google map to find the distance b/w any two points of any location



If you need such a information from code then try the below code.
In my another blog i already show you how to find the Latitude and Longitude of any point so Reusing the previous information we again create a Java based solution to find the distance.

I write a code to implement the Haversine formula which 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 "triangles".

Below is the code of implementing the formula

----------------------------------------- start code ----------------------------------------------------------------------

  double getDistByHaversine(double lat1, double lon1, double lat2, double lon2, String unit)
    {
        double dLat  =lat2 - lat1;// -2.20306276 = -1.10153138
        double dLong = lon2 - lon1;// 1.28540039
   
        double a =Math.sin(this.deg2rad(dLat/2)) * Math.sin(this.deg2rad(dLat/2)) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(this.deg2rad(dLong/2)) * Math.sin(this.deg2rad(dLong/2));// -0.01922417 * -0.01922417 + 0.83214027 * 0.85284337 * 0.01121700 * 0.01121700 = 0.00036957 + 0.00008929 = 0.00045886
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));// = 2 * atan2(0.02142102,0.99977054) = 2 * 0.021422658624589 = 0.04284532
   
        return 6378.7*c;  //= 273.29742514 kms from ibd to lhr
    }


        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts decimal degrees to radians             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }

        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        /*::  This function converts radians to decimal degrees             :*/
        /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
        private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
        }


 public static void main(String a[])
    {
 TestDistance ob=new TestDistance();

// find the latitude and longitude from first example
 System.out.println(ob.getDistByHaversine(Double.parseDouble("32.9697"), Double.parseDouble("-96.80322"), Double.parseDouble("29.46786"), Double.parseDouble("-98.53506"), "K") + " km\n");

---------------------------------------- End code -------------------------------------------------------------------------- 

Enjoy Google with JAVA.

No comments:

Post a Comment