forked from jasonwinn/haversine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Haversine.java
37 lines (30 loc) · 1.09 KB
/
Haversine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Jason Winn
* http://jasonwinn.org
* Created July 10, 2013
*
* Description: Small class that provides approximate distance between
* two points using the Haversine formula.
*
* Call in a static context:
* Haversine.distance(47.6788206, -122.3271205,
* 47.6788206, -122.5271205)
* --> 14.973190481586224 [km]
*
*/
public class Haversine {
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double distance(double startLat, double startLong,
double endLat, double endLong) {
double dLat = Math.toRadians((endLat - startLat));
double dLong = Math.toRadians((endLong - startLong));
startLat = Math.toRadians(startLat);
endLat = Math.toRadians(endLat);
double a = haversin(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversin(dLong);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c; // <-- d
}
public static double haversin(double val) {
return Math.pow(Math.sin(val / 2), 2);
}
}