Skip to content

Instantly share code, notes, and snippets.

@aatishnn
Created April 19, 2018 12:21
Show Gist options
  • Save aatishnn/1e4575fd147404cc357ea547cb4dd536 to your computer and use it in GitHub Desktop.
Save aatishnn/1e4575fd147404cc357ea547cb4dd536 to your computer and use it in GitHub Desktop.
Get CSV of POI around an Area using Google Maps API
import time
import csv
import googlemaps
types = ['airport', 'amusement_park', 'bank', 'bus_station',
'shopping_mall', 'gas_station', 'hospital', 'department_store']
useful_fields = (
'id', 'formatted_address', 'place_id', 'types', 'name', 'rating')
extra_fields = ('latitude', 'longitude', 'poi_type')
class POIGenerator(object):
def __init__(self, key, poi_type, pages_to_go=5):
"""
Args:
key: Google Maps Key
pages_to_go: Number of pages to get from results
"""
self.gmaps = googlemaps.Client(key=key)
self.pages_to_go = pages_to_go
self.poi_list = []
self.poi_type = poi_type
self.run()
def add_poi(self, results):
normalized_results = []
for r in results:
new_r = {k: v for k, v in r.items() if k in useful_fields}
new_r['latitude'] = r['geometry']['location']['lat']
new_r['longitude'] = r['geometry']['location']['lng']
new_r['poi_type'] = self.poi_type
normalized_results.append(new_r)
self.poi_list += normalized_results
def run(self):
current_page = 0
next_page_token = None
while current_page < self.pages_to_go:
params = {
'location': "27.7172,85.3240",
'radius': 11000,
'type': self.poi_type,
'query': None
}
if next_page_token:
params['page_token'] = next_page_token
print("sending request with params: ", str(params))
places = self.gmaps.places(**params)
self.add_poi(places['results'])
next_page_token = places.get('next_page_token', None)
if not next_page_token:
break
# this is done because doc says:
# There is a short delay between when a next_page_token is issued,
# and when it will become valid
time.sleep(3)
current_page += 1
def get_poi_list(self):
return self.poi_list
with open('poi.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=useful_fields + extra_fields)
writer.writeheader()
for poi_type in types:
poi_list = POIGenerator(
key='<YOUR_API_KEY>',
poi_type=poi_type
).get_poi_list()
writer.writerows(poi_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment