Forked from danielgomezrico/DistanceCalculator.java
Created
February 20, 2018 13:58
-
-
Save culjo/e683a86732c4f1c31ce25ee331deab6a to your computer and use it in GitHub Desktop.
Java / Android - calculate the distance between two coordinates with great circle formula.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment