Skip to content

Instantly share code, notes, and snippets.

@isfaaghyth
Created December 3, 2018 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isfaaghyth/93c60a84ada410b768fa303e809dfbf2 to your computer and use it in GitHub Desktop.
Save isfaaghyth/93c60a84ada410b768fa303e809dfbf2 to your computer and use it in GitHub Desktop.
public class HaversineFormula {
static double lat1, lat2, deg;
public HaversineFormula() {}
public static double calculate(double initialLat, double initialLong, double finalLat, double finalLong){
int R = 6371; // km
double dLat = toRadians(finalLat - initialLat);
double dLon = toRadians(finalLong - initialLong);
lat1 = toRadians(lat1);
lat2 = 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.atan2(Math.sqrt(a), Math.sqrt(1-a));
return (int) Math.round((R * c) * 100)/(double) 100;
}
public static double toRadians(double deg) {
return deg * (Math.PI/180);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment