dlflannery commited on
Commit
7100257
·
verified ·
1 Parent(s): da8f14f

Create geo_distance.py

Browse files
Files changed (1) hide show
  1. geo_distance.py +70 -0
geo_distance.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ from urllib.parse import quote
4
+ import math
5
+ from typing import Union
6
+ from time import sleep
7
+
8
+
9
+ def get_geo_coords(address, access_token):
10
+ sleep_time = 1
11
+ while sleep_time < 10:
12
+ base_url = "https://us1.locationiq.com/v1/search"
13
+ # headers= {"key: " + f"{access_token}", "Content-Type: application/json",}
14
+ url = f"{base_url}?key={access_token}&q={quote(address)}&format=json"
15
+ response = requests.get(url)
16
+ if response.status_code == 429:
17
+ sleep(sleep_time)
18
+ sleep_time *= 3
19
+ else:
20
+ break
21
+ if sleep_time > 9:
22
+ return (0.0, 0.0)
23
+ rjson = json.loads(response.content)
24
+ return (float(rjson[0]['lat']), float(rjson[0]['lon']))
25
+
26
+
27
+
28
+ Number = Union[int, float]
29
+
30
+ def great_circle_distance_miles(lat1: Number, lon1: Number, lat2: Number, lon2: Number,
31
+ radius_miles: float = 3958.8) -> float:
32
+ """
33
+ Compute the great-circle distance between two points on the Earth using the haversine formula.
34
+
35
+ Parameters:
36
+ - lat1, lon1: Latitude and longitude of the first point in degrees.
37
+ - lat2, lon2: Latitude and longitude of the second point in degrees.
38
+ - radius_miles: Radius of the Earth in miles (default 3958.8 miles).
39
+
40
+ Returns:
41
+ - Distance between the two points in miles (float).
42
+
43
+ Notes:
44
+ - Latitude values should be in [-90, 90], longitude values in [-180, 180].
45
+ """
46
+ # convert degrees to radians
47
+ phi1 = math.radians(lat1)
48
+ phi2 = math.radians(lat2)
49
+ dphi = math.radians(lat2 - lat1)
50
+ dlambda = math.radians(lon2 - lon1)
51
+
52
+ # haversine formula
53
+ a = math.sin(dphi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2
54
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
55
+
56
+ return radius_miles * c
57
+
58
+ # Example:
59
+ # Distance from New York City (40.7128° N, -74.0060° W)
60
+ # to Los Angeles (34.0522° N, -118.2437° W)
61
+ # if __name__ == "__main__":
62
+ # ny_lat, ny_lon = 40.7128, -74.0060
63
+ # la_lat, la_lon = 34.0522, -118.2437
64
+ # print(f"NYC -> LA: {great_circle_distance_miles(ny_lat, ny_lon, la_lat, la_lon):.1f} miles")
65
+ # if __name__ == "__main__":
66
+ # address = 'Grytviken, South Georgia' #'Rio de Janerio, Argentina'
67
+ # (lat, lon) = get_geo_coords(address) #'307 Pauly Drive, Englewood, Ohio, USA')
68
+ # print(f'{address}: Lat = {float(lat):.2f}, Lon = {float(lon):.2f}')
69
+
70
+