0

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?

4
  • What are those errors? Are you by any chance concatenating floats and strings? Commented Feb 5, 2015 at 17:48
  • @OliverW. I get a Str indices must be integer error. Commented Feb 5, 2015 at 17:55
  • please add the full traceback, so that we may see where that error pops up, rather than having to track your code. Commented Feb 5, 2015 at 17:58
  • @OliverW. Here you go: dpaste.com/1Y02ZQ2 Commented Feb 5, 2015 at 18:02

1 Answer 1

3

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'])
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Thanks for the explanation and correction! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.