Skip to content

Instantly share code, notes, and snippets.

@jdickinson202
Forked from srosenthal/computeDistances.py
Created May 4, 2017 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdickinson202/c341a1c97e6365082f2557cd0d8a7f09 to your computer and use it in GitHub Desktop.
Save jdickinson202/c341a1c97e6365082f2557cd0d8a7f09 to your computer and use it in GitHub Desktop.
A Python script that prints the distance between an origin and multiple destinations
#!/usr/bin/env python
from optparse import OptionParser
import csv
import json
import StringIO
import sys
import urllib
# Print the distance between an origin and multiple destinations.
def main(cmdline=None):
parser = make_parser()
opts, args = parser.parse_args(cmdline)
# Read the CSV file into a %-encoded string and a string array
origin = ""
destinations = []
with open(args[0], 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if reader.line_num == 1:
origin = urllib.quote(row[0])
destinations.append(urllib.quote(row[1]))
# Call Google Maps -- Distance Matrix API and get back JSON result
jsonResult = urllib.urlopen(
"http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + '|'.join(destinations) +
"&sensor=false&units=imperial").read()
# Parse JSON result to get the distances in miles
result = json.loads(jsonResult)
# We have only one row (origin) but several destinations (columns)
distances = []
for column in result['rows'][0]['elements']:
distances.append(column['distance']['value'] / 1609.34) # m/mile
# Print a CSV result with a third column -- distances in miles
output = StringIO.StringIO()
writer = csv.writer(output)
for i in range(0, len(distances)):
writer.writerow([
urllib.unquote(origin),
urllib.unquote(destinations[i]),
distances[i]])
print output.getvalue()
return 0
def make_parser():
usage = """%prog: [csvFile]
Print the distance between an origin and multiple destinations.
Provide a CSV file with the following information:
The origin (e.g. "Los Angeles, CA") in the first cell
and the destinations in cells of the second column."""
parser = OptionParser(usage)
return parser
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment