I am trying to search for the first hotel for each of these coordinates below
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]]
I tried the following codes
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)
when I tried to print out each of the hotel's name I got an error.
print(first_hotels["results"][0]["name"])
IndexError: list index out of range
Anyone got any idea what's wrong? Here is the documentation I used https://developers.google.com/maps/documentation/places/web-service/search-nearby
CodePudding user response:
You're defining the parameters outside of the loop, and are passing the entire list target_locations
. Update the parameters inside the loop:
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)