首页 > 解决方案 > 为什么 Google 会返回“无”坐标

问题描述

所以我正在尝试获取格拉斯哥的坐标,并且我正在尝试使用谷歌地图 API。但是,这些函数返回 None 和 None 作为坐标,我不太明白为什么。我假设我在某处有错误的参数。代码如下。

import requests
api_key = api key
google_api_key = api key
def get_coordinates(api_key, address, verbose=False):
    try:
        url = 'https://maps.googleapis.com/maps/api/geocode/json?key={}&address={}'.format(api_key, address)
        response = requests.get(url).json()
        if verbose:
            print('Google Maps API JSON result =>', response)
        results = response['results']
        geographical_data = results[0]['geometry']['location'] # get geographical coordinates
        lat = geographical_data['lat']
        lon = geographical_data['lng']
        return [lat, lon]
    except:
        return [None, None]

address = 'Glasgow, United Kingdom'
glasgow_centre = get_coordinates(google_api_key, address)
print('Coordinate of {}: {}'.format(address, glasgow_centre))

标签: pythonapijupyter

解决方案


发生索引错误是因为您没有任何结果。

记录响应以查看您收到的错误消息。这就是发生在我身上的事情:

{'error_message': '此 API 项目无权使用此 API。', 'results': [], 'status': 'REQUEST_DENIED'}


推荐阅读