haversine

Haversine formula implementation in Java

The Haversine algorithm is used to calculate the distance between two points of which we know their longitude and latitude. Below we include a Java method that implements this formula returning the distance in meters:

private static int calculateDistanceByHaversineFormula(double lon1, double lat1, double lon2, double lat2) {
double earthRadius = 6371; // km

s(lat1);
lon1 = Math.toRadians(lon1);
lat2 = Math.toRadians(lat2);
lon2 = Math.toRadians(lon2);

double dlon = (lon2 - lon1);
double dlat = (lat2 - lat1);

double sinlat = Math.sin(dlat / 2);
double sinlon = Math.sin(dlon / 2);

double a = (sinlat * sinlat) + Math.cos(lat1)*Math.cos(lat2)*(sinlon*sinlon);
double c = 2 * Math.asin (Math.min(1.0, Math.sqrt(a)));

double distanceInMeters = earthRadius * c * 1000;
return (int) distanceInMeters;
}

In our case it has been used to evaluate the distance to a given establishment from our current position (calculated by GPS).

Contact

    La mejor solución de firma electrónica para tu empresa

    Update cookies preferences
    Scroll to Top