Use google places api to search for nearby places on a queried address.
I built this app to evaluate buildings (looking for schools and metro nearby)
# Crosscompute
address = "1724 church avenue brooklyn, ny"
radius_int = 600
target_folder = '.'
search_queries_select = """
subway_station
school
accounting
airport
amusement_park
aquarium
art_gallery
atm
bakery
bank
bar
beauty_salon
bicycle_store
book_store
bowling_alley
bus_station
cafe
campground
car_dealer
car_rental
car_repair
car_wash
casino
cemetery
church
city_hall
clothing_store
convenience_store
courthouse
dentist
department_store
doctor
electrician
electronics_store
embassy
fire_station
florist
funeral_home
furniture_store
gas_station
gym
hair_care
hardware_store
hindu_temple
home_goods_store
hospital
insurance_agency
jewelry_store
laundry
lawyer
library
liquor_store
local_government_office
locksmith
lodging
meal_delivery
meal_takeaway
mosque
movie_rental
movie_theater
moving_company
museum
night_club
painter
park
parking
pet_store
pharmacy
physiotherapist
plumber
police
post_office
real_estate_agency
restaurant
roofing_contractor
rv_park
school
shoe_store
shopping_mall
spa
stadium
storage
store
subway_station
synagogue
taxi_stand
train_station
transit_station
travel_agency
university
veterinary_care
zoo"""
from itertools import takewhile
search_queries = takewhile(lambda x: x.strip(), search_queries_select.strip().split('\n'))
search_queries = [s.strip() for s in search_queries]
radius = radius_int
queried_building_pixel_size = 20
nearby_places_pixel_size = 10
from os.path import join
import geopy
import numpy as np
import pandas as pd
import requests
from pandas import DataFrame
from functools import partial
GOOGLE_KEY = 'AIzaSyAJ_nmWU9pkqXuqSiLCj8dgO3WqbiXBRug'
def get_nearby_places(lat, lng, search_query, radius=radius):
location = f'{lat},{lng}'
# places search api
places_api = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json'
params = dict(
location=location,
radius=radius,
type=search_query,
key=GOOGLE_KEY)
results = requests.get(places_api, params=params).json()['results']
return results
def get_n_distinct_colors(n):
MAX_VALUE = (256 ** 3) - 1
colors = np.linspace(0, MAX_VALUE, n, endpoint=True, dtype=np.int)
return ['#{}'.format(hex(I)[2:].zfill(6)) for I in colors]
# geocode address
from geopy.geocoders.googlev3 import GeocoderQuotaExceeded
from time import sleep
google_geo = geopy.GoogleV3()
for i in range(3):
try:
location = google_geo.geocode(address)
break
except GeocoderQuotaExceeded:
print('geocoder quota exceeded, trying again')
sleep(3)
continue
else:
print('geocoder.error = GeocoderQuotaExceeded')
raise GeocoderQuotaExceeded
lat, lng = location.latitude, location.longitude
colors = get_n_distinct_colors(len(search_queries) + 1)
c, colors = colors[0], colors[1:]
header = ('description', 'latitude', 'longitude', 'FillColor', 'radius_in_pixels')
data = dict(zip(header, ['origin', lat, lng, c, queried_building_pixel_size]))
origin = DataFrame(data, index=['queried building'])
dfs = []
query_place = partial(get_nearby_places, lat=lat, lng=lng, radius=radius)
for color, q in zip(colors, search_queries):
r = query_place(search_query=q)
df = DataFrame(r)
df['latitude'] = df['geometry'].apply(lambda x: x['location']['lat'])
df['longitude'] = df['geometry'].apply(lambda x: x['location']['lng'])
df['description'] = df['types'].apply(lambda x: x[0])
df = df.set_index('name')
df = df[['description', 'latitude', 'longitude']]
df['FillColor'] = color
dfs.append(df)
places = pd.concat([origin] + dfs)
places['radius_in_pixels'] = nearby_places_pixel_size
places.index.name = 'Name'
places.head()
target_path = join(target_folder, 'places.csv')
places.to_csv(target_path)
print('places_geotable_path = ' + target_path)