Skip to content

Instantly share code, notes, and snippets.

@bshillingford
Created August 21, 2013 22:55
Show Gist options
  • Save bshillingford/6301267 to your computer and use it in GitHub Desktop.
Save bshillingford/6301267 to your computer and use it in GitHub Desktop.
"""
Google Directions API
"""
import urllib2
import urllib
import json
class Modes:
DRIVING="driving"
WALKING="walking"
BICYCLING="bicycling"
TRANSIT="transit"
class Avoid:
TOLLS="tolls"
HIGHWAYS="highways"
class Units:
METRIC="metric"
IMPERIAL="imperial"
class Region:
"""Not exhaustive, any two-character ccTLD top level domain value works."""
Canada="ca"
UnitedStates="us"
class DirectionsException(Exception):
def __init__(self, response):
Exception.__init__(self, response['status'])
self.response = response
self.status = response['status']
def directions(origin, destination, region=None, units=None, mode=None, avoid=None, departure_time=None, arrival_time=None, sensor=False):
options = dict(origin=origin,
destination=destination,
sensor="true" if sensor else "false")
if region:
options["region"] = region
if units:
options["units"] = units
if mode:
options["mode"] = mode
if avoid:
options["avoid"] = avoid
if departure_time:
options["departure_time"] = departure_time
if arrival_time:
options["arrival_time"] = arrival_time
url = "http://maps.googleapis.com/maps/api/directions/json?" + urllib.urlencode(options)
try:
conn = urllib2.urlopen(url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError as error:
try:
raise DirectionsException(json.loads(error.read()))
except ValueError:
raise DirectionsException({'status': "cannot decode JSON, bad connection?"})
if response['status'] != "OK":
raise DirectionsException(response)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment