索引错误:列出超出范围的索引(用于将地址转换为地理坐标的 Python 程序



我尝试使用以下代码将地址转换为地理坐标,但出现以下错误。

Traceback (most recent call last):
File "/tmp/sessions/cac34a57fd2090d2/main.py", line 7, in <module>
my_geo = results[0]['geometry']['location']
IndexError: list index out of range

这是我编写的代码:

import requests
geo_url = 'http://maps.googleapis.com/maps/api/geocode/json'
my_address = {'address': '45 Ramkrishana Road,East Burdwan, West Bengal, India', 
'language': 'en'}
response = requests.get(geo_url, params = my_address)
results = response.json()['results']
my_geo = results[0]['geometry']['location']
print("Longitude:",my_geo['lng'],"n","Latitude:",my_geo['lat'])

要使用 Google 地图 API,您需要一个 API 密钥,这要求您设置结算帐号。你有 API 密钥吗?Google 作为示例提供的 API 的可能查询字符串如下所示:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

如您所见,最后一个参数是您的 API 密钥,这是必需的。如果不传递 API 密钥,响应将如下所示:

{
"error_message" : "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account",
"results" : [],
"status" : "REQUEST_DENIED"
}

results将是一个空列表,因此IndexError.

相关内容

  • 没有找到相关文章

最新更新