First, you’ll need to make sure you have the
googlemaps package installed. You can do this by running
pip install googlemaps in your terminal.
Once you have the package installed, you can use the following code:
from datetime import datetime
Replace ‘YOUR_API_KEY’ with your actual API key
gmaps = googlemaps.Client(key=’YOUR_API_KEY’)
Ask for user input of two locations
origin = input(“Enter the starting location: “)
destination = input(“Enter the destination location: “)
Call the Directions API to get the distance
now = datetime.now()
directions_result = gmaps.directions(origin, destination, mode=”driving”, departure_time=now)
Extract the distance from the result
distance = directions_result[‘legs’][‘distance’][‘text’]
Print the distance
print(“The distance between”, origin, “and”, destination, “is”, distance)
In this program, we first import the necessary packages:
datetime. We then create a
gmaps object using our API key.
Next, we ask the user for input of two locations: the starting location and the destination location.
We then call the
directions method of our
gmaps object, passing in the origin and destination locations as well as the mode of transportation (in this case, driving) and the departure time (which we set to the current time).
The result of the
directions method call is a JSON object containing information about the route between the two locations, including the distance. We extract the distance from the result and print it out to the user.
Note that you will need to replace
'YOUR_API_KEY' with your actual API key, which you can obtain from the Google Cloud Console.