-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_addresses.py
More file actions
80 lines (70 loc) · 2.24 KB
/
map_addresses.py
File metadata and controls
80 lines (70 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import csv
import sys
import argparse
import webbrowser
import http.server
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
import _thread
import time
import googlemaps
from geojson import Feature, FeatureCollection, Point
def start_server():
httpd = HTTPServer(('127.0.0.1', 3600), SimpleHTTPRequestHandler)
httpd.serve_forever()
parser = argparse.ArgumentParser(description="""Command line utility to geolocate and map a text file of addresses""")
parser.add_argument('-i', help="Input file of complete mailing addesses")
parser.add_argument('-m', help="Add map marker for median of mapped addresses",
action = "store_true")
parser.add_argument('-key', help="Text file with Google Maps API key", type=argparse.FileType("r"))
args = parser.parse_args()
outfile = "mapped_addresses.csv"
raw_key = args.key.read().rstrip("\n")
gmaps = googlemaps.Client(key= raw_key)
features = []
lats = []
longs = []
with open(args.i) as csvfile:
csvfile.__next__()
reader = csv.reader(csvfile, delimiter = ",")
for row in reader:
base_address = row[1] + "," + row[2] + ", " + row[3] + ", " + row[4]
try:
gr = gmaps.geocode(base_address)
latitude = gr[0]['geometry']['location']['lat']
longitude = gr[0]['geometry']['location']['lng']
except IndexError:
latitude, longitude = '', ''
lats.append(latitude)
longs.append(longitude)
features.append(
Feature(
geometry = Point((longitude,latitude)),
properties = {
'name': row[0],
'address': row[1]
}
)
)
lat_mean = sum(lats)/len(lats)
long_mean = sum(longs)/len(longs)
if args.m:
features.append(
Feature(
geometry = Point((long_mean, lat_mean)),
properties = {
'name': "median"
}
)
)
collection = FeatureCollection(features)
with open("map.geojson", "w") as f:
f.write('%s' % collection)
_thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
sys.exit(0)