Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Client for Google Maps Services's Places couldn't pass Page_Token

I'm trying out Python Client for Google Maps Services to pull a list of places using Places API.

Here is the GitHub page: https://github.com/googlemaps/google-maps-services-python Here is the documentation page: https://googlemaps.github.io/google-maps-services-python/docs/2.4.4/#module-googlemaps.exceptions

In the .places def, I need to enter page_token in string format in order to get next 10 listings. When I run the codes below, it kept showing me INVALID_REQUEST

Here is my code:

places_result = gmaps.places(query="hotels in Singapore", page_token='')
for result in places_result['results']:
    print(result['name'])
try :
places_result = gmaps.places(query="hotels in Singapore", page_token=places_result['next_page_token'])
except ApiError as e:
    print(e)
else:
    for result in places_result['results']:
    print(result['name'])
like image 856
Johnny Koh Avatar asked Dec 19 '22 13:12

Johnny Koh


1 Answers

Alright, after hours of trial and error. I noticed I need to add a time.sleep(2) to make it work. I'm not sure why but it works.

It failed with time.sleep(1), time.sleep(2) and above will solve the problem.

Hopefully someone can shed some light to the reason behind.

Here is my code that works to retrieve Places and go to the next page until the end. Remember to replace 1. your key at 'YOUR KEY HERE' and 2. the string you want to search at 'SEARCH SOMETHING'.

import googlemaps
import time

gmaps = googlemaps.Client(key='YOUR KEY HERE')

def printHotels(searchString, next=''):
    try:
        places_result = gmaps.places(query=searchString, page_token=next)
    except ApiError as e:
        print(e)
    else:
        for result in places_result['results']:
            print(result['name'])
    time.sleep(2)
    try:
        places_result['next_page_token']
    except KeyError as e:
        print('Complete')
    else:
        printHotels(searchString, next=places_result['next_page_token'])

if __name__ == '__main__':
    printHotels('SEARCH SOMETHING')
like image 118
Johnny Koh Avatar answered May 19 '23 17:05

Johnny Koh