Calculate great circle distance between two points in a sphere, given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula We know that the globe is "sort of" spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth
(lat1: float, lon1: float, lat2: float, lon2: float)
| 6 | |
| 7 | |
| 8 | def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float: |
| 9 | """ |
| 10 | Calculate great circle distance between two points in a sphere, |
| 11 | given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula |
| 12 | |
| 13 | We know that the globe is "sort of" spherical, so a path between two points |
| 14 | isn't exactly a straight line. We need to account for the Earth's curvature |
| 15 | when calculating distance from point A to B. This effect is negligible for |
| 16 | small distances but adds up as distance increases. The Haversine method treats |
| 17 | the earth as a sphere which allows us to "project" the two points A and B |
| 18 | onto the surface of that sphere and approximate the spherical distance between |
| 19 | them. Since the Earth is not a perfect sphere, other methods which model the |
| 20 | Earth's ellipsoidal nature are more accurate but a quick and modifiable |
| 21 | computation like Haversine can be handy for shorter range distances. |
| 22 | |
| 23 | Args: |
| 24 | * `lat1`, `lon1`: latitude and longitude of coordinate 1 |
| 25 | * `lat2`, `lon2`: latitude and longitude of coordinate 2 |
| 26 | Returns: |
| 27 | geographical distance between two points in metres |
| 28 | |
| 29 | >>> from collections import namedtuple |
| 30 | >>> point_2d = namedtuple("point_2d", "lat lon") |
| 31 | >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227) |
| 32 | >>> YOSEMITE = point_2d(37.864742, -119.537521) |
| 33 | >>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters" |
| 34 | '254,352 meters' |
| 35 | """ |
| 36 | # CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System |
| 37 | # Distance in metres(m) |
| 38 | # Equation parameters |
| 39 | # Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation |
| 40 | flattening = (AXIS_A - AXIS_B) / AXIS_A |
| 41 | phi_1 = atan((1 - flattening) * tan(radians(lat1))) |
| 42 | phi_2 = atan((1 - flattening) * tan(radians(lat2))) |
| 43 | lambda_1 = radians(lon1) |
| 44 | lambda_2 = radians(lon2) |
| 45 | # Equation |
| 46 | sin_sq_phi = sin((phi_2 - phi_1) / 2) |
| 47 | sin_sq_lambda = sin((lambda_2 - lambda_1) / 2) |
| 48 | # Square both values |
| 49 | sin_sq_phi *= sin_sq_phi |
| 50 | sin_sq_lambda *= sin_sq_lambda |
| 51 | h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda)) |
| 52 | return 2 * RADIUS * asin(h_value) |
| 53 | |
| 54 | |
| 55 | if __name__ == "__main__": |
no test coverage detected