Google Directions API, Full App¶
Contents¶
Indices and tables¶
Exercise¶
For this week, the goal is to create a direction printing function that does the following:
It should accept a parsed json dictionary from last week’s function.
It should return a formatted string with travel instructions:
Include the instructions, distant and duration
Also include the manuever, but replace it with an appropriate unicode arrow!
- A good reference for unicode arrows is here, though note that not all of them will render correctly.
This will require using the str.format()
function.
On completion of this exercise, you should have a finished application that does the following:
- Accepts the arguments outlined in part 1 from the command lines
- Support the output and load arguments outlined in part 3
- Print each step of a trip including arrows instead of text manuevers
Hints¶
To help you get started, here is one possible signature for the output function:
def format_output(parsed):
"""
Demonstration of parsing input json and using the data to print directions
:param parsed: The nested dictionary representation of the JSON file.
"""
Additionally, here is the bottom of the file, where the function calls are to the file is run:
if __name__ == '__main__':
try:
arguments = parsing_example()
except ValueError as err:
# Can remove this to show the full error output
print(err)
exit(1)
# If the load parameter value is not the default than load the file.
if arguments['load'] != "":
# The usual way to work with files in python, this takes care of closing the file
# after using it.
with open(arguments['load']) as json_in:
res = json_in.read()
# Otherwise query the api.
else:
try:
res = http_request(arguments['start'], arguments['end'], arguments['waypoint'])
except (requests.ConnectionError, requests.Timeout) as err:
print(err)
exit(1)
if arguments['output'] != '':
# 'wb' for writing a binary file.
with open(arguments['output'], 'wb') as outfile:
outfile.write(res)
try:
json_dictionary = parse_json(res)
format_output(json_dictionary)
except IOError as err:
print(err)
exit(1)