Skip to content

Instantly share code, notes, and snippets.

@adl1995
Last active May 30, 2024 23:34
Show Gist options
  • Save adl1995/a66fa3532364ff87aaaec72be332abe7 to your computer and use it in GitHub Desktop.
Save adl1995/a66fa3532364ff87aaaec72be332abe7 to your computer and use it in GitHub Desktop.
A Python script for fetching a JSON list of points of interests using the Google Maps Places API and writing them to a CSV file. Example query "things to do split".
#!/usr/bin/env python
import csv
import json
import requests
import argparse
# Add parameter for the search query.
parser = argparse.ArgumentParser()
parser.add_argument('query', type=str, help='Search query for Google Maps API')
args = parser.parse_args()
# Fetch the data.
places = requests.get(f'https://maps.googleapis.com/maps/api/place/textsearch/json?query={args.query}&language=en&key=API_KEY')
# Convert the response to a JSON object.
places = json.loads(places.text)['results']
# Make the filename more readable, as this will appear as the layer title in Google My Maps.
query = args.query.split(' ')
filename = ' '.join([q.capitalize() for q in query])
columns = ['name', 'coordinates', 'types', 'rating', 'formatted address', 'icon']
with open(f'places/france-south/{filename}.csv', 'w') as out_file:
writer = csv.writer(out_file, delimiter=',')
writer.writerow(columns)
for place in places:
name = place['name']
icon = place['icon']
formatted_address = place['formatted_address']
if 'rating' in place:
rating = place['rating']
else:
rating = -1
types = ', '.join(place['types'])
lat, lng = place['geometry']['location']['lat'], place['geometry']['location']['lng']
data = [name, (lat, lng), types, rating, formatted_address, icon]
print(f'{filename} -> {data}')
writer.writerow(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment