42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
|
import requests
|
||
|
|
||
|
def get_lat_lng(api_key, address):
|
||
|
base_url = "https://api.opencagedata.com/geocode/v1/json"
|
||
|
params = {
|
||
|
'q': address,
|
||
|
'key': api_key,
|
||
|
}
|
||
|
|
||
|
response = requests.get(base_url, params=params)
|
||
|
data = response.json()
|
||
|
|
||
|
if response.status_code == 200 and data['status']['code'] == 200:
|
||
|
location = data['results'][0]['geometry']
|
||
|
return location['lat'], location['lng']
|
||
|
else:
|
||
|
print(f"Error: {data['status']['message']}")
|
||
|
return None, None
|
||
|
|
||
|
def get_lat_lng_for_addresses(api_key, addresses):
|
||
|
coordinates = []
|
||
|
|
||
|
for address in addresses:
|
||
|
lat, lng = get_lat_lng(api_key, address)
|
||
|
if lat is not None and lng is not None:
|
||
|
coordinates.append((lat, lng))
|
||
|
|
||
|
return coordinates
|
||
|
|
||
|
# Replace 'YOUR_API_KEY' with your OpenCage Geocoding API key
|
||
|
api_key = '744ad0d2d58e49d1ac57d6fb04fe5d82'
|
||
|
|
||
|
# Example list of addresses
|
||
|
addresses = ["1600 Amphitheatre Parkway, Mountain View, CA",
|
||
|
"Eiffel Tower, Paris, France",
|
||
|
"Big Ben, London, UK"]
|
||
|
|
||
|
coordinates = get_lat_lng_for_addresses(api_key, addresses)
|
||
|
|
||
|
# Print the coordinates
|
||
|
for address, coord in zip(addresses, coordinates):
|
||
|
print(f"{address} -> Latitude: {coord[0]}, Longitude: {coord[1]}")
|