Search code examples
javageolocationdistance

Calculate distance between two GeoLocation


I am trying to calculate the distance between two Geo Locations. The problem I have is the following: I tried with libraries like :Geocalc and Haversine formulas, like this:

public static final double RKilometers = 6371;

public static double calculationByDistance(double lat1, double lon1, double lat2, double lon2) {
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lon2 - lon1);
    lat1 = Math.toRadians(lat1);
    lat2 = Math.toRadians(lat2);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    double c = 2 * Math.asin(Math.sqrt(a));
    return RKilometers * c;
}

But I get the same wrong values with all those options. For short distances it works perfectly, but for long distances it doesn´t.

This is the test I did:

//distance between Barrow Island(Australia) and Tavatave(Madagascar)
assertEquals(calculationByDistance(20.82, 115.4, 18.15, 49.4), 6885, 20);
//get 6875.965169284442

//here is the problem
//distance between Rio Grande and Glasgow
assertEquals(calculationByDistance(32.05, 52.11, 55.83, 4.25), 10744, 20);
//get 4522.502442756569

Does someone know where is my error? Thank you!


Solution

  • I found the error. The problem was the values for latitud and longitud were wrong. I took the data from Wolframalpha and they don´t show the signs for the values. The rights values for my test are:

    assertEquals(calculationByDistance(-32.05, 52.11, 55.83, -4.25), 10744, 20); 
    

    Thank you for your time!!!And sorry for the stupid error :)