I am trying to reverse geocode 500 lat and long random points using google API. I wrote the code below but I notice there are some errors that I need help with. I want to create a output CSV that has the Lat/Long and complete address of the reverse geocode and also the JSON geo_Data. Some of the errors is that my Ouput CSV is not being written and I don't know how to parse out just the address to my output CSV. Can anyone help me?
Script cited below:
import pandas as pd
import json
import requests
df = pd.read_csv('/Users/albertgonzalobautista/Desktop/Amsterdam_RP500_2.csv')
# create new columns
df['geocode_data'] = ''
df['address']=''
# function that handles the geocoding requests
def reverseGeocode(latlng):
result = {}
apikey = 'XXX'
url = f'https://maps.googleapis.com/maps/api/geocode/json?latlng={latlng}&key={apikey}'
r = requests.get(url)
r.raise_for_status()
data = r.json()
if data['results']:
result = data['results'][0]
return result
for i, row in df.iterrows():
df['geocode_data'][i] = reverseGeocode(df['lat'][i].astype(str) + ',' + df['lon'][i].astype(str))
for i, row in df.iterrows():
if 'address_components' in row['geocode_data']:
for component in row['geocode_data']['address_components']:
df.to_csv('testingGEO233.csv', encoding='utf-8', index=False)