apis




Pay Notebook Creator: Salah Ahmed0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

evaluate points of interest

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)

In [2]:
# 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"""
In [3]:
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
In [4]:
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
In [5]:
GOOGLE_KEY = 'AIzaSyAJ_nmWU9pkqXuqSiLCj8dgO3WqbiXBRug'
In [6]:
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
In [7]:
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]
In [11]:
# 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
geocoder quota exceeded, trying again
geocoder quota exceeded, trying again
In [8]:
colors = get_n_distinct_colors(len(search_queries) + 1)
c, colors = colors[0], colors[1:]
In [9]:
header = ('description', 'latitude', 'longitude', 'FillColor', 'radius_in_pixels')
data = dict(zip(header, ['origin', lat, lng, c, queried_building_pixel_size]))
In [10]:
origin = DataFrame(data, index=['queried building'])
In [11]:
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'
In [12]:
places.head()
Out[12]:
<style> .dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; } </style>
FillColor description latitude longitude radius_in_pixels
Name
queried building #000000 origin 40.649206 -73.963177 10
Church Av Station #7fffff subway_station 40.649523 -73.963284 10
Beverley Rd #7fffff subway_station 40.644229 -73.964498 10
Erasmus Hall High School #ffffff school 40.649581 -73.958197 10
Children's Center-Early Learning #ffffff school 40.648211 -73.965457 10
In [13]:
target_path = join(target_folder, 'places.csv')
places.to_csv(target_path)
print('places_geotable_path = ' + target_path)
places_geotable_path = ./places.csv