import requests import json from urllib.parse import quote import math from typing import Union from time import sleep def get_geo_coords(address, access_token): sleep_time = 1 while sleep_time < 10: base_url = "https://us1.locationiq.com/v1/search" # headers= {"key: " + f"{access_token}", "Content-Type: application/json",} url = f"{base_url}?key={access_token}&q={quote(address)}&format=json" response = requests.get(url) if response.status_code != 200: # == 429: sleep(sleep_time) sleep_time *= 3 else: break if sleep_time > 9: return (0.0, 0.0) rjson = json.loads(response.content) return (float(rjson[0]['lat']), float(rjson[0]['lon'])) Number = Union[int, float] def great_circle_distance_miles(lat1: Number, lon1: Number, lat2: Number, lon2: Number, radius_miles: float = 3958.8) -> float: """ Compute the great-circle distance between two points on the Earth using the haversine formula. Parameters: - lat1, lon1: Latitude and longitude of the first point in degrees. - lat2, lon2: Latitude and longitude of the second point in degrees. - radius_miles: Radius of the Earth in miles (default 3958.8 miles). Returns: - Distance between the two points in miles (float). Notes: - Latitude values should be in [-90, 90], longitude values in [-180, 180]. """ # convert degrees to radians phi1 = math.radians(lat1) phi2 = math.radians(lat2) dphi = math.radians(lat2 - lat1) dlambda = math.radians(lon2 - lon1) # haversine formula a = math.sin(dphi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return radius_miles * c # Example: # Distance from New York City (40.7128° N, -74.0060° W) # to Los Angeles (34.0522° N, -118.2437° W) # if __name__ == "__main__": # ny_lat, ny_lon = 40.7128, -74.0060 # la_lat, la_lon = 34.0522, -118.2437 # print(f"NYC -> LA: {great_circle_distance_miles(ny_lat, ny_lon, la_lat, la_lon):.1f} miles") # if __name__ == "__main__": # address = 'Grytviken, South Georgia' #'Rio de Janerio, Argentina' # (lat, lon) = get_geo_coords(address) #'307 Pauly Drive, Englewood, Ohio, USA') # print(f'{address}: Lat = {float(lat):.2f}, Lon = {float(lon):.2f}')