使用Python / GoogleMaps API反向地理编码:如何解析响应

时间:2018-04-09 04:03:42

标签: python google-maps google-geocoding-api

我正在尝试使用Google Maps Geocoding API通过Python脚本查找与纬度和经度相关联的州。从服务器获取响应没有问题,但是当我这样做时,我无法提取所需的信息。

This is my code:

from pymongo import MongoClient
import googlemaps

client = MongoClient()
turnkey = "MYVERYSECRETAPICODEWOOOOOOOOO"
gmaps = googlemaps.Client(key=turnkey)

lat = 29
long = -98.4936

#This code runs fine:
geocode = gmaps.reverse_geocode((lat, long))
print(geocode[0]['address_components'])
print("\n")
print(geocode[0]['address_components'][0])
print(geocode[0]['address_components'][0]["types"])

#This Code Is a Problem:
for i in geocode[0]['address_components'][:]:
    print(geocode[0]["address_components"][i])

    if 'administrative_area_level_1' in geocode[0]['address_components'][i]['types'] :
        print(geocode[0]['address_components'][i]['long_name'])

我收到的回复是:

Traceback (most recent call last):
[{'long_name': '6476', 'short_name': '6476', 'types': ['street_number']}, {'long_name': 'East Fm 476', 'short_name': 'E Fm 476', 'types': ['route']}, {'long_name': 'Pleasanton', 'short_name': 'Pleasanton', 'types': ['locality', 'political']}, {'long_name': 'Atascosa County', 'short_name': 'Atascosa County', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Texas', 'short_name': 'TX', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'United States', 'short_name': 'US', 'types': ['country', 'political']}, {'long_name': '78064', 'short_name': '78064', 'types': ['postal_code']}]

  File "C:/Users/Pendelluft/Documents/CodeyMcCodeFace/CodeyCode/SNAKESSSSS/SingleQuery.py", line 24, in <module>

    print(geocode[0]["address_components"][i])
{'long_name': '6476', 'short_name': '6476', 'types': ['street_number']}
['street_number']
TypeError: list indices must be integers or slices, not dict

Process finished with exit code 1

我没有得到的是为什么当我要求它打印地理编码[0] ['address_components'] [0] [“类型”]时工作正常,但抱怨我正在处理像字典一样的列表我尝试geocode [0] ['address_components'] [i] ['types']。

非常感谢任何帮助,非常感谢你们的时间。

1 个答案:

答案 0 :(得分:0)

你的错误是python语法:

代码已解决

for x in geocode[0]['address_components']:
    print(x)

    if 'administrative_area_level_1' in x['types'] :
        print(x['long_name'])