2015-02-05 70 views
0

我試圖在反向地理編碼Google Maps API中找到['locality', 'political']值。在python中對地理編碼API響應進行迭代

我可以達到同樣在Javascript如下:

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 
    } 
}); 

使用Python,我試過如下:

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']) 

這給了我一堆錯誤。我無法繞過響應對象找到['locality', 'political']值來查找相關城市short_name。我該如何解決這個問題?

+0

那些是什麼錯誤?你有沒有機會[連接浮動和字符串](https://stackoverflow.com/questions/26540270/cannot-concatenate-str-and-float-objects)? – 2015-02-05 17:48:26

+0

@OliverW。我得到一個'STR索引必須是整數'錯誤。 – Newtt 2015-02-05 17:55:38

+0

請添加完整的回溯,以便我們可以看到*哪裏*那個錯誤彈出,而不是必須跟蹤您的代碼。 – 2015-02-05 17:58:23

回答

2

您試圖訪問一個字典的鍵,而是你迭代該鍵的字符:

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

results是一本字典(從city_components=線明顯)。當您鍵入for c in results時,您將綁定c到該字典的鍵(依次)。這意味着c是一個字符串(在你的場景中,很可能所有的鍵都是字符串)。因此,然後鍵入c['types']無厘頭:您要訪問的值/屬性字符串'types' ...

最有可能你想要的東西:

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']) 
+0

工作就像一個魅力。感謝您的解釋和更正! :) – Newtt 2015-02-05 18:56:43