Last active
July 14, 2023 12:15
-
-
Save JonathanGarro/7c7803cc422a14cea217a3b74d7cf9a0 to your computer and use it in GitHub Desktop.
Get admin info from list of coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import pandas as pd | |
from geopy.geocoders import OpenCage | |
# insert your OpenCage API key | |
geocoder = OpenCage('<YOUR_API_KEY_HERE>') | |
# load locations with pandas | |
location_data = 'largest_cities_coordinates.csv' | |
data = pd.read_csv(location_data) | |
# create placeholder list and counter | |
list_admin_info = [] | |
counter = 0 | |
# loop over each location and extract whatever available admin data API returns | |
for index, row in data.iterrows(): | |
try: | |
temp_dict = {} | |
latitude = row['Latitude'] | |
longitude = row['Longitude'] | |
location = geocoder.reverse((latitude, longitude), exactly_one=True) | |
temp_dict['index'] = counter + 1 | |
temp_dict['lat'] = latitude | |
temp_dict['lon'] = longitude | |
temp_dict['admin1'] = location.raw['components'].get('state', 'N/A') | |
temp_dict['admin2'] = location.raw['components'].get('city', 'N/A') | |
temp_dict['admin3'] = location.raw['components'].get('neighbourhood', 'N/A') | |
temp_dict['confidence'] = location.raw.get('confidence', 'N/A') | |
list_admin_info.append(temp_dict) | |
except: | |
pass | |
finally: | |
counter += 1 | |
# save output to new csv - change name as needed | |
keys = list_admin_info[0].keys() | |
a_file = open("output.csv", "w") | |
dict_writer = csv.DictWriter(a_file, keys) | |
dict_writer.writeheader() | |
dict_writer.writerows(list_admin_info) | |
a_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment