Search code examples
androidgeolocationgpsgeocodinggeopositioning

GPS calculate distance using GeoUtils library works well in India but didnt work in USA for android


I have code which works in India well. This code calculate the approximate distance between two locations. I used the code mentioned below. But If i run this same code in USA. Then for every location updates calculates the different distance. I passed the source and destination latitude and longitude to this function.The app works well in India. But not works in USA. At same place it shows different calculations. Thanks in advance.Any help will be appreciate.

public static double distanceKm(double lat1, double lon1, double lat2, double lon2) {
        double lat1Rad = Math.toRadians(lat1);
        double lat2Rad = Math.toRadians(lat2);
        double deltaLonRad = Math.toRadians(lon2 - lon1);
        return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad)
                * Math.cos(deltaLonRad))
                * 6371;
    }  

Solution

  • The formula is the greater circle formula.
    It is well known, that it does not work well for small distances.
    The reason is this part:

    Math.cos(deltaRad).  
    

    This is a cosinus for a very small value, which is numerically "ill conditioned": They do not work well on computers. (Nowadays with double precision the effect is less visible) Therfore for small distances the haversine formula is better suited.

    If you still would have problems with the haversine distance formula, then obviously your input data is the problem. (e.g if read from GPS without proper pre filtering)

    The chance is high that your implemetation although using greater circle variant delivers correct result. Chances are high that your claimed "correct distance" is wrong.