closest-points




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

Closest Points

This tool retrieves closest points to a given location

author: salah

{address ? location} {csv_url_table : points ? spreadsheet with a minimum of 3 columns: Location, Latitude, and Longitude}

In [5]:
#crosscompute
address = '1724 church avenue Brooklyn, NY 11226'
target_folder = '.'
csv_url_table_path = 'example/NYC_Wi-Fi_Hotspot_Locations.csv'

show_standard_error = True
In [1]:
import sys
import geopy
import pandas as pd
import pysal

from argparse import ArgumentParser
from os.path import join
from pysal.cg.kdtree import KDTree

class MissingColumnException(Exception):
    pass

def get_closest_spots(coordinates, locations):
    ''' use kdtree to get closest points'''
    tree = KDTree(locations.values,
                  distance_metric='Arc',
                  radius=pysal.cg.RADIUS_EARTH_MILES)
    distances, indices = tree.query(coordinates, k=10)
    # get all points within half mile
    # indices = tree.query_ball_point(coordinates, 0.5)
    # print(data.ix[indices]['ssid'])
    return distances, indices

geocoder = geopy.GoogleV3()
try:
    _, coordinates = geocoder.geocode(address)
except ValueError as e:
    print('geocode exception raised: %s' % e)
    sys.exit()

data = pd.read_csv(csv_url_table_path)
try:
    locations = data[['Latitude', 'Longitude']]
except KeyError as e:
    error = '''missing "Latitude" and/or "Longitude"
            columns in csv data: %s''' % e
    raise MissingColumnException(error)
distances, indices = get_closest_spots(coordinates, locations)
columns = ['name', 'latitude', 'longitude',
           'FillColor', 'RadiusInMeters']
geomap = []
geomap.append([address, coordinates[0], coordinates[1], 'blue', 15])
try:
    data = [[i[0], i[1], i[2], 'red', 10]
            for i in
            data.ix[indices][['Location', 'Latitude', 'Longitude']].values]
except KeyError as e:
    error = 'missing "Location" column in csv data: %s' % e
    raise MissingColumnException(error)
geomap.extend(data)
path = join(target_folder, 'geo.csv')
pd.DataFrame(geomap, columns=columns).to_csv(path, index=False)
print("points_geotable_path = {0}".format(path))