Spatial Algorithms




Pay Notebook Creator: Roy Hyunjin Han0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

Define Geometry from Addresses

Use this tool to convert a list of addresses into a LineString or Polygon in WKT format.

{ address_text : Addresses ? Place each address on a separate line }

In [20]:
# CrossCompute
target_folder = '/tmp'
address_text_path = 'addresses.txt'
In [6]:
addresses = open(address_text_path).read().splitlines()
addresses
Out[6]:
['2435 Grand Concourse, Bronx, NY 10468',
 '126 E 13th St, New York, NY 10003',
 '22 W 34th St, New York, NY 10001',
 '37 W 26th St, New York, NY 10010',
 '500 8th Ave, New York, NY 10018']
In [9]:
from geopy import GoogleV3

def get_lonlat(address):
    # Convert address to latitude and longitude
    geocode = GoogleV3('AIzaSyDNqc0tWzXHx_wIp1w75-XTcCk4BSphB5w').geocode
    location = geocode(address)
    return location.longitude, location.latitude
In [10]:
xys = [get_lonlat(_) for _ in addresses]
xys
Out[10]:
[(-73.8982975, 40.8612969),
 (-73.988742, 40.7327127),
 (-73.9864111, 40.7489334),
 (-73.99045149999999, 40.744581),
 (-73.99253329999999, 40.7529737)]
In [17]:
from shapely.geometry import LineString
line = LineString(xys)
line
Out[17]:
<shapely.geometry.linestring.LineString at 0x7fefc945ed68>
In [18]:
from shapely.geometry import Polygon
polygon = Polygon(xys + [xys[0]])
polygon
Out[18]:
<shapely.geometry.polygon.Polygon at 0x7fefc945ef28>
In [24]:
wkts = [
    line.wkt,
    polygon.wkt,
]
Out[24]:
['LINESTRING (-73.8982975 40.8612969, -73.988742 40.7327127, -73.9864111 40.7489334, -73.99045149999999 40.744581, -73.99253329999999 40.7529737)',
 'POLYGON ((-73.8982975 40.8612969, -73.988742 40.7327127, -73.9864111 40.7489334, -73.99045149999999 40.744581, -73.99253329999999 40.7529737, -73.8982975 40.8612969))']
In [25]:
target_path = target_folder + '/wkts.txt'
open(target_path, 'wt').write('\n'.join(wkts))
print('geometry_text_path = %s' % target_path)
geometry_text_path = /tmp/wkts.txt
In [26]:
import pandas as pd
target_path = target_folder + '/map.csv'
pd.DataFrame(wkts, columns=['wkt']).to_csv(target_path, index=False)
print('geometry_geotable_path = %s' % target_path)
geometry_geotable_path = /tmp/map.csv

Generated LineString and Polygon in WKT Format

{ geometry_text : Generated LineString and Polygon in WKT Format }

{ geometry_geotable : Map of Generated LineString and Polygon }