Newtt
Newtt

Reputation: 6200

Iterating through Geocoding API response in python

I'm trying to find the ['locality', 'political'] value in the reverse geocoding Google Maps API.

I could achieve the same in Javascript as follows:

var formatted = data.results;
$.each(formatted, function(){
     if(this.types.length!=0){
          if(this.types[0]=='locality' && this.types[1]=='political'){
               address_array = this.formatted_address.split(',');
          }else{
               //somefunction
          }
     }else{
         //somefunction
     }
});

Using Python, I tried the following:

url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&result_type=locality&key='+MAPS_API_KEY
results = json.loads(urllib.request.urlopen(url).read().decode('utf-8'))
city_components = results['results'][0]
for c in results:
    if c['types']:
        if c['types'][0] == 'locality':
            print(c['types'])

This gives me a bunch of errors. I'm not able to get my head around iterating through the response object to find the ['locality', 'political'] value to find the related City short_name. How do I go about solving this?

Upvotes: 0

Views: 849

Answers (1)

Oliver W.
Oliver W.

Reputation: 13459

You are trying to access the keys of a dictionary, but instead you are iterating over the characters of that key:

for c in results:
    if c['types']:

results is a dictionary (obvious from your city_components= line). When you type for c in results, you are binding c to the keys of that dictionary (in turn). That means c is a string (in your scenario, most likely all the keys are strings). So then typing c['types'] does not make sense: you are trying to access the value/attribute 'types' of a string...

Most likely you wanted:

for option in results['results']:
    addr_comp = option.get('address_components', [])
    for address_type in addr_comp:
        flags = address_type.get('types', [])
        if 'locality' in flags and 'political' in flags:
            print(address_type['short_name'])

Upvotes: 3

Related Questions