Created
March 27, 2020 23:08
-
-
Save ggdio/ecd6d497d5a4d6db7b3036da73503c9b to your computer and use it in GitHub Desktop.
Trying to calculate the distance between two coordinates
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
public class CoordDistance { | |
public static void main(String[] args) { | |
System.out.println("Results:"); | |
System.out.println(distance(32.9697, -96.80322, 32.9697, -94.80323, Unit.METERS) + " Meters\n"); | |
} | |
/** | |
* Calculates distance between coordinates | |
* | |
* @param lat1 - First Latitude | |
* @param lon1 - First Longitude | |
* @param lat2 - Second Latitude | |
* @param lon2 - Second Longitude | |
* @param unit - Unit to consider | |
* | |
* @return Distance in specified {@link Unit} | |
*/ | |
private static double distance(double lat1, double lon1, double lat2, double lon2, Unit unit) { | |
double delta = lon1 - lon2; | |
double sin = (Math.sin(calcRadians(lat1)) * Math.sin(calcRadians(lat2))); | |
double cos = (Math.cos(calcRadians(lat1)) * Math.cos(calcRadians(lat2)) * Math.cos(calcRadians(delta))); | |
double distance = calcDegrees(Math.acos(sin + cos)) * 60 * 1.1515; | |
return unit.apply(distance); | |
} | |
/** | |
* Converts decimal degrees to radians | |
* @param degrees | |
* @return radians | |
*/ | |
private static double calcRadians(double degrees) { | |
return (degrees * Math.PI / 180.0); | |
} | |
/** | |
* Converts radians to decimal degrees | |
* @param radians | |
* @return decimal degrees | |
*/ | |
private static double calcDegrees(double radians) { | |
return (radians * 180.0 / Math.PI); | |
} | |
private static enum Unit { | |
MILES(dist -> dist), | |
KILOMETERS(dist -> dist * 1.609344), | |
METERS(dist -> KILOMETERS.apply(dist) * 1000) | |
; | |
private final Function<Double, Double> function; | |
private Unit(Function<Double, Double> function) { | |
this.function = function; | |
} | |
public Double apply(Double millesDist) { | |
return this.function.apply(millesDist); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment