diff --git a/mbta_finder.py b/mbta_finder.py index 3ce9df8..13c6992 100755 --- a/mbta_finder.py +++ b/mbta_finder.py @@ -10,6 +10,7 @@ import urllib # urlencode function import urllib2 # urlopen function (better than urllib version) import json +from pprint import pprint # Useful URLs (you need to add the appropriate parameters for your requests) @@ -25,8 +26,11 @@ 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 - + f = urllib2.urlopen(url) + response_text = f.read() + response_data = json.loads(response_text) + return response_data + def get_lat_long(place_name): """ @@ -36,8 +40,12 @@ def get_lat_long(place_name): See https://developers.google.com/maps/documentation/geocoding/ for Google Maps Geocode API URL formatting requirements. """ - pass + processed_name = ["+" if c == " " else c for c in place_name] + url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + "".join(processed_name) # + "&key=" + + infodump = get_json(url) + return (infodump['results'][0]['geometry']['location']['lat'],infodump['results'][0]['geometry']['location']['lng']) +# pprint(get_lat_long("Fenway Park, Massachusetts")) def get_nearest_station(latitude, longitude): """ @@ -47,7 +55,11 @@ def get_nearest_station(latitude, longitude): See http://realtime.mbta.com/Portal/Home/Documents for URL formatting requirements for the 'stopsbylocation' API. """ - pass + url = "http://realtime.mbta.com/developer/api/v2/stopsbylocation?api_key=" + MBTA_DEMO_API_KEY + "&lat=" + str(latitude) + "&""lon=" + str(longitude) + "&format=json" + infodump = get_json(url) + return (str(infodump['stop'][0]['stop_name']),str(infodump['stop'][0]['distance']) + " miles") +# geoinfo = get_lat_long("Fenway Park, Massachusetts") +# print(get_nearest_station(geoinfo[0],geoinfo[1])) def find_stop_near(place_name): @@ -55,5 +67,8 @@ 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 + location = get_lat_long(place_name) #location is a (lat,long) tuple + return "Location: " + str(location) + "\n" + "Stop: " + str(get_nearest_station(location[0],location[1])) + +print find_stop_near("Fenway Park, Massachusetts")