Reverse Geocoding using Python and Google API
Question: 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 = {}
        url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng={0}&key={1}'
        apikey = 'XXX'
        request = url.format(latlng, apikey)
        data = json.loads(requests.get(request).text)
        if len(data['results']) > 0:
            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)
    


Answer: You don't have any code in this for loop

    
    
    for component in row['geocode_data']['address_components']:
    

maybe try this

    
    
    for component in row['geocode_data']['address_components']:
        df['address'] = row['geocode_data']['address_components']
    

You might actually want a string instead of a list of the components:

    
    
    for component in row['geocode_data']['address_components']:
        df['address'] = row['geocode_data']['formatted_address']
    

