Skip to content

Instantly share code, notes, and snippets.

@danielgomezrico
Last active January 6, 2021 00:37
Show Gist options
  • Save danielgomezrico/992c2f35d04a42a99ea5 to your computer and use it in GitHub Desktop.
Save danielgomezrico/992c2f35d04a42a99ea5 to your computer and use it in GitHub Desktop.
Java / Android - calculate the distance between two coordinates with great circle formula.
import static java.lang.Math.acos;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
/**
* Calculate distance between coordinates.
*/
public class DistanceCalculator {
static double PI_RAD = Math.PI / 180.0;
/**
* Use Great Circle distance formula to calculate distance between 2 coordinates in meters.
*/
public double greatCircleInFeet(LatLng latLng1, LatLng latLng2) {
return greatCircleInKilometers(latLng1.latitude, latLng1.longitude, latLng2.latitude,
latLng2.longitude) * 3280.84;
}
/**
* Use Great Circle distance formula to calculate distance between 2 coordinates in meters.
*/
public double greatCircleInMeters(LatLng latLng1, LatLng latLng2) {
return greatCircleInKilometers(latLng1.latitude, latLng1.longitude, latLng2.latitude,
latLng2.longitude) * 1000;
}
/**
* Use Great Circle distance formula to calculate distance between 2 coordinates in kilometers.
* https://software.intel.com/en-us/blogs/2012/11/25/calculating-geographic-distances-in-location-aware-apps
*/
public double greatCircleInKilometers(double lat1, double long1, double lat2, double long2) {
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));
}
}
@irfanirawangits
Copy link

Nice bro. Thanks

@jishps
Copy link

jishps commented Aug 10, 2018

nice

@dinohubijar
Copy link

Isn't Line #12 in Feet, not Meters?
Thanks anyways 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment