Skip to content

Commit 36c1792

Browse files
committed
implemented haversine
1 parent 4866b13 commit 36c1792

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

geodesy/haversine_distance.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from math import asin, atan, cos, sin, sqrt, tan, pow, radians
2+
3+
4+
def haversine_distance(lat1, lon1, lat2, lon2):
5+
"""
6+
Calculate great circle distance between two points in a sphere,
7+
given longitudes and latitudes.
8+
(https://en.wikipedia.org/wiki/Haversine_formula)
9+
10+
Args:
11+
lat1, lon1: latitude and longitude of coordinate 1
12+
lat2, lon2: latitude and longitude of coordinate 2
13+
returnAngle: Toggle to return distance or angle
14+
15+
Returns:
16+
geographical distance between two points in metres
17+
18+
>>> int(haversine_distance(37.774856, -122.424227, 37.864742, -119.537521)) # From SF to Yosemite
19+
254352
20+
21+
"""
22+
23+
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
24+
AXIS_A = 6378137.0
25+
AXIS_B = 6356752.314245
26+
RADIUS = 6378137
27+
28+
# Equation parameters
29+
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
30+
flattening = (AXIS_A - AXIS_B) / AXIS_A
31+
phi_1 = atan((1 - flattening) * tan(radians(lat1)))
32+
phi_2 = atan((1 - flattening) * tan(radians(lat2)))
33+
lambda_1 = radians(lon1)
34+
lambda_2 = radians(lon2)
35+
36+
# Equation
37+
sin_sq_phi = pow(sin((phi_2 - phi_1) / 2), 2)
38+
sin_sq_lambda = pow(sin((lambda_2 - lambda_1) / 2), 2)
39+
h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda))
40+
41+
distance = 2 * RADIUS * asin(h_value)
42+
43+
return distance
44+
45+
46+
if __name__ == "__main__":
47+
import doctest
48+
49+
doctest.testmod()

0 commit comments

Comments
 (0)