The Haversine formula is a mathematical tool used to calculate the distance between two points on the surface of a sphere, such as the Earth, whose longitude and latitude are known. This method is essential in geolocation and GPS navigation applications. In this Viafirma article, we will explore how to implement this formula in Java, providing practical examples and ready-to-use code.
How to implement the Haversine Formula in Java
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).