从 Python 中的 Google Geocoding API 获取特定字段

我正在使用 google geocoding api 来填写我有部分信息的一些位置的信息。

例如,我有这个部分信息,我正在尝试获取国家/地区和州:

geocode_result = gmaps.geocode('lindero cerro verde caracas 1080')

输出如下:

[{'address_components': [{'long_name': 'Calle El Lindero','short_name': 'Calle El Lindero','types': ['route']},{'long_name': 'Caracas','short_name': 'CCS','types': ['locality','political']},{'long_name': 'El Hatillo','short_name': 'El Hatillo','types': ['administrative_area_level_2',{'long_name': 'Miranda','short_name': 'Miranda','types': ['administrative_area_level_1',{'long_name': 'Venezuela','short_name': 'VE','types': ['country',{'long_name': '1083','short_name': '1083','types': ['postal_code']}],'formatted_address': 'Calle El Lindero,Caracas 1083,Miranda,Venezuela','geometry': {'bounds': {'northeast': {'lat': 10.4543027,'lng': -66.83872099999999},'southwest': {'lat': 10.4505117,'lng': -66.8454213}},'location': {'lat': 10.4519725,'lng': -66.84174039999999},'location_type': 'GEOMETRIC_CENTER','viewport': {'northeast': {'lat': 10.4543027,'lng': -66.8454213}}},'place_id': 'ChIJ2XE6pHdYKowRKnEB09XALo4',{'address_components': [{'long_name': 'Calle El Lindero','geometry': {'bounds': {'northeast': {'lat': 10.4513741,'lng': -66.83886060000002},'southwest': {'lat': 10.4510553,'lng': -66.8390758}},'location': {'lat': 10.4511532,'lng': -66.83892469999999},'viewport': {'northeast': {'lat': 10.4525636802915,'lng': -66.83761921970851},'southwest': {'lat': 10.4498657197085,'lng': -66.84031718029152}}},'place_id': 'ChIJZRnObHZYKowR--st9lrM0pw','types': ['route']}]

我将如何获得国家(委内瑞拉)和州(米兰达)?

wpz731 回答:从 Python 中的 Google Geocoding API 获取特定字段

我认为这就是你想要的:-

geocode_result = gmaps.geocode('lindero cerro verde caracas 1080')

for d in geocode_result[0]['address_components']:
    t = d.get('types')
    if t is not None and t[0] == 'country':
        print(d['long_name'])
        break

从您的示例来看, geocode_result 是一个只有一个元素的列表。如果它比这更复杂,您需要相应地调整此代码

本文链接:https://www.f2er.com/27866.html

大家都在问