Search code examples
pythonpandasgoogle-mapsgoogle-maps-api-3

Access bulk business data via Google Maps API with python


I'm trying to access google maps data from Google maps API. This code generates an empty xlsx file. Instead, it should return data. What do you think I do wrong?

Thanks in advance for help.


import googlemaps
import pandas as pd
import time


API_KEY = open('API_KEY.txt', 'r').read()
map_client = googlemaps.Client(API_KEY)

location = (53.53921005946531, -113.50032556307899)
search_string = 'halal restaurants'
distance = 25
edmonton_restaurants = []

response = map_client.places_nearby(
    location = location,
    keyword= search_string,
    name='halal_restaurants',
    radius= distance
)

edmonton_restaurants.extend(response.get('results'))
next_page_token = response.get('next_page_token')

while next_page_token:
    time.sleep(3)
    response = map_client.places_nearby(
        location = location,
        keyword= search_string,
        name='halal_restaurants',
        radius= distance,
        page_token=next_page_token
    )
    edmonton_restaurants.extend(response.get('results'))
    next_page_token = response.get('next_page_token')

df = pd.DataFrame(edmonton_restaurants)
df.to_excel('edmoton_rest.xlsx'.format(search_string), index=False)

Solution

  • You are using the wrong API. You are using the Places Nearby API, which is not the same as the Places API. The Places Nearby API is for finding places near a location, not for searching for places. You need to use the Places API. You can find the documentation here.

    The Places API has a different response format than the Places Nearby API. The Places API returns a list of places, while the Places Nearby API returns a list of places and a next page token. You can find the documentation for the Places API here.

    The correct code would have the following replacement:

    response = map_client.places(
        query = search_string,
        location = location,
        radius= distance
    )
    
    edmonton_restaurants.extend(response.get('results'))
    next_page_token = response.get('next_page_token')
    
    while next_page_token:
        time.sleep(3)
        response = map_client.places(
            query = search_string,
            location = location,
            radius= distance,
            page_token=next_page_token
        )
        edmonton_restaurants.extend(response.get('results'))
        next_page_token = response.get('next_page_token')
    
    df = pd.DataFrame(edmonton_restaurants)