首页 > 解决方案 > 在 Python 中解析 Google Maps API 结果

问题描述

我编写了一个脚本来解析来自 Google Maps API 结果的结果,以从中获取特定部分。在我的具体情况下,我需要地理位置。以下是 Google 地图的响应结构示例:

{'address_components': [{'long_name': '253',
   'short_name': '253',
   'types': ['street_number']},
  {'long_name': 'Broadway', 'short_name': 'Broadway', 'types': ['route']},
  {'long_name': 'Manhattan',
   'short_name': 'Manhattan',
   'types': ['political', 'sublocality', 'sublocality_level_1']},
  {'long_name': 'New York',
   'short_name': 'New York',
   'types': ['locality', 'political']},
  {'long_name': 'New York County',
   'short_name': 'New York County',
   'types': ['administrative_area_level_2', 'political']},
  {'long_name': 'New York',
   'short_name': 'NY',
   'types': ['administrative_area_level_1', 'political']},
  {'long_name': 'United States',
   'short_name': 'US',
   'types': ['country', 'political']},
  {'long_name': '10007', 'short_name': '10007', 'types': ['postal_code']}],
 'formatted_address': '253 Broadway, New York, NY 10007, USA',
 'geometry': {'location': {'lat': 40.7133073, 'lng': -74.0073864},
  'location_type': 'ROOFTOP',
  'viewport': {'northeast': {'lat': 40.71465628029149,
    'lng': -74.00603741970849},
   'southwest': {'lat': 40.7119583197085, 'lng': -74.00873538029151}}},
 'place_id': 'ChIJ9wzTpBhawokRWLkRYU6k64E',
 'plus_code': {'compound_code': 'PX7V+82 New York, United States',
  'global_code': '87G7PX7V+82'},
 'types': ['premise']}

这是我的代码

def get_geocode(address_data):
    for item in address_data['location']:
        typs = set(item['types'])

        if typs == set(['premise']):

            return item['location']

    return None

你能建议一种更好的方法来解析结果吗?据我了解,这些集合仅在地址组件内的第一个列表中划分字典,所以我不太确定如何解析它之后的所有内容。

我想得到的输出是:'lat':40.7133073,'lng':-74.0073864,单独或一行。

标签: pythonpython-3.xpandasgoogle-mapsfor-loop

解决方案


推荐阅读