Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import urllib.parse
- import requests
- main_api = "https://www.mapquestapi.com/directions/v2/route?"
- key =
- def show_error(status, message):
- print('******************************************')
- print(f'Status Code: {str(status)}; {message}')
- print('******************************************\n')
- def row_builder(value, longest_str, last=""):
- return f'{value}{" " * ((longest_str) - len(value))}{last}'
- while True:
- orig = input("Starting Location: ")
- if orig in ["q", "orig"]:
- break
- dest = input("Destination: ")
- if dest in ["q", "quit"]:
- break
- url = main_api + urllib.parse.urlencode({
- "key": key,
- "from": orig,
- "to": dest,
- })
- print("URL: " + url)
- json_data = requests.get(url).json()
- json_status = json_data["info"]["statuscode"]
- if json_status == 0:
- kms = []
- narratives = []
- for route in json_data["route"]["legs"][0]["maneuvers"]:
- kms.append(f' {str("{:.2f}".format((route["distance"]) * 1.61))} km ')
- narratives.append(f' {route["narrative"]} ')
- longest_narrative_str = len(max(narratives, key=len))
- longest_kms = len(max(kms, key=len))
- headers = f'|{row_builder(" Distance", longest_kms)}|{row_builder(" Directions", longest_narrative_str)}|'
- print(f'API Status: {str(json_status)} = A successful route call.\n\n'
- f'=========================================\n'
- f'Directions from {orig} to {dest}\n'
- f'Trip Duration:\t\t{json_data["route"]["formattedTime"]}\n'
- f'Kilometers:\t\t\t{str("{:.2f}".format((json_data["route"]["distance"]) * 1.61))}\n'
- f'Fuel Used (Ltr):\t{str("{:.2f}".format((json_data["route"]["fuelUsed"]) * 3.78))}\n'
- f'=========================================\n')
- print(f'+{"-" * longest_kms}+{"-" * longest_narrative_str}+')
- print(headers)
- print(f'+{"-" * longest_kms}+{"-" * longest_narrative_str}+')
- for i in range(0, len(kms)):
- print(f'|{row_builder(kms[i], longest_kms)}|{row_builder(narratives[i], longest_narrative_str)}|')
- print(f'+{"-" * longest_kms}+{"-" * longest_narrative_str}+')
- elif json_status == 402:
- show_error(json_status, "Invalid user inputs from one or both location")
- elif json_status == 611:
- show_error(json_status, "Missing an entry for one or both locations")
- else:
- print('************************************************************')
- print(f'FOr Status Code: {str(json_status)}; Refer to:')
- print('https://developer.mapquest.com/documentation/directions-api/status-codes')
- print('*************************************************************\n')
Advertisement
Add Comment
Please, Sign In to add comment