使用Google Places API搜索坐标列表中第一家酒店的名称



我正在为下面的每个坐标搜索第一家酒店

target_locations = [[-18.3693, 26.5019],
[51.3813, 1.3862],
[40.8106, 111.6522],
[-17.65, -62.75],
[49.6383, -1.5664],
[38.4661, 68.8053],
[43.9098, 67.2495],
[45.55, 2.3167],
[55.756, -4.8556]]

我尝试了以下代码

target_search = "Hotel"
radius = 5000
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
my_params  = {
"location": target_locations,
"keyword": target_search,
"radius": radius,
"key": g_key
}
# Search for the first hotel in each coordinate
for loc in locations: 
first_hotels = requests.get(base_url,params = my_params).json()
time.sleep(1)

当我试图打印出每一家酒店的名字时,我都弄错了。

print(first_hotels["results"][0]["name"])

IndexError:列出索引超出范围

有人知道怎么了吗?这是我使用的文档https://developers.google.com/maps/documentation/places/web-service/search-nearby

您在循环之外定义参数,并传递整个列表target_locations。更新循环内的参数:

import requests
target_locations = [[-18.3693, 26.5019],
[51.3813, 1.3862],
[40.8106, 111.6522],
[-17.65, -62.75],
[49.6383, -1.5664],
[38.4661, 68.8053],
[43.9098, 67.2495],
[45.55, 2.3167],
[55.756, -4.8556]]
target_search = "Hotel"
radius = 5000
base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
# Search for the first hotel in each coordinate
for loc in target_locations:

my_params  = {
"location": loc, # pass a single location only
"keyword": target_search,
"radius": radius,
"key": g_key
}

first_hotels = requests.get(base_url,params = my_params).json()
time.sleep(1)

最新更新