Spaces:
Running
Running
Create geo_distance.py
Browse files- geo_distance.py +41 -0
geo_distance.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Union
|
| 3 |
+
|
| 4 |
+
Number = Union[int, float]
|
| 5 |
+
|
| 6 |
+
def great_circle_distance_miles(lat1: Number, lon1: Number, lat2: Number, lon2: Number,
|
| 7 |
+
radius_miles: float = 3958.8) -> float:
|
| 8 |
+
"""
|
| 9 |
+
Compute the great-circle distance between two points on the Earth using the haversine formula.
|
| 10 |
+
|
| 11 |
+
Parameters:
|
| 12 |
+
- lat1, lon1: Latitude and longitude of the first point in degrees.
|
| 13 |
+
- lat2, lon2: Latitude and longitude of the second point in degrees.
|
| 14 |
+
- radius_miles: Radius of the Earth in miles (default 3958.8 miles).
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
- Distance between the two points in miles (float).
|
| 18 |
+
|
| 19 |
+
Notes:
|
| 20 |
+
- Latitude values should be in [-90, 90], longitude values in [-180, 180].
|
| 21 |
+
"""
|
| 22 |
+
# convert degrees to radians
|
| 23 |
+
phi1 = math.radians(lat1)
|
| 24 |
+
phi2 = math.radians(lat2)
|
| 25 |
+
dphi = math.radians(lat2 - lat1)
|
| 26 |
+
dlambda = math.radians(lon2 - lon1)
|
| 27 |
+
|
| 28 |
+
# haversine formula
|
| 29 |
+
a = math.sin(dphi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2
|
| 30 |
+
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
| 31 |
+
|
| 32 |
+
return radius_miles * c
|
| 33 |
+
|
| 34 |
+
# Example:
|
| 35 |
+
# Distance from New York City (40.7128° N, -74.0060° W)
|
| 36 |
+
# to Los Angeles (34.0522° N, -118.2437° W)
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
ny_lat, ny_lon = 40.7128, -74.0060
|
| 39 |
+
la_lat, la_lon = 34.0522, -118.2437
|
| 40 |
+
print(f"NYC -> LA: {great_circle_distance_miles(ny_lat, ny_lon, la_lat, la_lon):.1f} miles")
|
| 41 |
+
|