From 001e398eff91aedc69e3264eed9cc2f0cb029fc6 Mon Sep 17 00:00:00 2001 From: jkunimune15 Date: Mon, 14 Mar 2016 19:05:00 -0400 Subject: [PATCH] Turning in my geocoding and web API toolbox --- mbta_finder.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/mbta_finder.py b/mbta_finder.py index 3ce9df8..1c5ee77 100755 --- a/mbta_finder.py +++ b/mbta_finder.py @@ -13,8 +13,8 @@ # Useful URLs (you need to add the appropriate parameters for your requests) -GMAPS_BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json" -MBTA_BASE_URL = "http://realtime.mbta.com/developer/api/v2/stopsbylocation" +GMAPS_BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?" +MBTA_BASE_URL = "http://realtime.mbta.com/developer/api/v2/stopsbylocation?" MBTA_DEMO_API_KEY = "wX9NwuHnZU2ToO7GmGR9uw" @@ -25,7 +25,7 @@ def get_json(url): Given a properly formatted URL for a JSON web API request, return a Python JSON object containing the response to that request. """ - pass + return urllib2.urlopen(url) def get_lat_long(place_name): @@ -36,8 +36,12 @@ def get_lat_long(place_name): See https://developers.google.com/maps/documentation/geocoding/ for Google Maps Geocode API URL formatting requirements. """ - pass - + f = get_json(GMAPS_BASE_URL+urllib.urlencode({'address':place_name})) + data = json.loads(f.read()) + try: + return (data['results'][0]['geometry']['location']['lat'], data['results'][0]['geometry']['location']['lng']) + except IndexError: + raise IndexError("Location not found!") def get_nearest_station(latitude, longitude): """ @@ -47,13 +51,21 @@ def get_nearest_station(latitude, longitude): See http://realtime.mbta.com/Portal/Home/Documents for URL formatting requirements for the 'stopsbylocation' API. """ - pass - + f = get_json(MBTA_BASE_URL+urllib.urlencode({"api_key":MBTA_DEMO_API_KEY,"lat":latitude,"lon":longitude,"format":"json"})) + data = json.loads(f.read()) + try: + return (data['stop'][0]['stop_name'], data['stop'][0]['distance']) + except IndexError: + raise IndexError("No stations were found near {},{}".format(latitude, longitude)) def find_stop_near(place_name): """ Given a place name or address, print the nearest MBTA stop and the distance from the given place to that stop. """ - pass + station = get_nearest_station(*get_lat_long(place_name)) + print "Station: "+station[0] + print "Distance: "+str(int(float(station[1])*1609.34))+" m" + +find_stop_near("4 Yawkey Way, Boston, MA 02215") \ No newline at end of file