For a project, I have a csv file with 60 coordinates and the radius (for each centroid of a city district) I want to get my Google Maps results of. Aim is to loop through the coordinates and the radius and receive all existing places of one certain type (e.g. cafes) for each of the listed coordinates. So far, I was able to retrieve the results with adding the coordinates manually and I'm struggling with applying the pandas 'apply' to my 'givePlaces'-function.
I used pandas to import the csv file and wrote a function that returns me the max. possible results (<60, Google doesn't allow more). I defined the variables "location", "radius" and "type". The code looks the following and almost works. Maybe one of you can help:
import googlemaps
import pprint
import time
import csv
import pandas as pd
from GoogleMapsAPIKey import get_my_key
#import the coordinates and radius csv-file
df = pd.read_csv('filepath',sep=';',header=0)
df
Simplified, the csv-table looks the like the following:
Latitude | Longitude | Radius |
---|---|---|
48.179037 | 11.522759 | 500 |
48.156327 | 11.414132 | 1200 |
#define my API Key
API_KEY = get_my_key()
gmaps = googlemaps.Client(key = API_KEY)
#Define a function that returns the Places API results:
def givePlaces(location, radius, type):
# define list of places of interest
places = []
# request first page
places_result = gmaps.places_nearby(location=location, radius=radius, type=type)
# add results to places
places = places places_result['results']
# while 'next_page_token' exists, request the next page and repeat
while('next_page_token' in places_result):
# wait 3 seconds before next request
time.sleep(3)
# overwrite places_result with results of second and/or third page
places_result = gmaps.places_nearby(page_token = places_result['next_page_token'])
# add these results to places
places = places places_result['results']
print("found " str(len(places)) " places")
return places
#Previously I used this manually:
location = 48.179037,11.522759
radius = 500
type = 'cafe'
my_places = givePlaces(location, radius, type)
#the apply function would look like this, but so far does not work:
df['places'] = df.apply(lambda row: givePlaces((row['Länge'], row['Breite'], row['Radius'], 'cafe'), axis=1)
pprint.pprint(my_places)
Can anyone kindly assist me with the pandas apply function? I'm still quite a beginner in coding and Google did not help much in my specific issue. Thank you so much in advance!
CodePudding user response:
3 things:
- don't name a variable
type
, as it is also a built-in python function df.apply(lambda row: givePlaces((row['Länge'], row['Breite'], row['Radius'], 'cafe'), axis=1)
is incorrectly formatted, it's missing a parenthesis and you need to pass location, as a string, dict, list or tuple.- The location needs to be specified as latitude (Breite),longitude (Länge)
Using a tuple that would make:
df.apply(lambda row: givePlaces((row['Breite'], row['Länge']), row['Radius'], 'cafe'), axis=1)