waypoints multiple location in python

To waypoint multiple locations using Google Maps API in Python, you can use the googlemaps module. Here's a sample code that demonstrates how to add multiple waypoints to a route using the API:

main.py
import googlemaps

# Define the API key
API_KEY = 'your_api_key_here'

# Define the client object
gmaps = googlemaps.Client(key=API_KEY)

# Define the origin and destination of the route
origin = 'Los Angeles, CA'
destination = 'San Francisco, CA'

# Define the waypoints for the route
waypoints = ['Santa Barbara, CA', 'Monterey, CA', 'Santa Cruz, CA']

# Define the route parameters
route_params = {
  'origin': origin,
  'destination': destination,
  'waypoints': waypoints,
  'optimize_waypoints': True,  # Optimizes the order of waypoints for fastest time
  'mode': 'driving'  # Specifies the mode of travel
}

# Call the API to get the directions
directions_result = gmaps.directions(**route_params)

# Extract and print the distance and duration of the route
route = directions_result[0]['legs'][0]
distance = route['distance']['text']
duration = route['duration']['text']
print(f'Distance: {distance}, Duration: {duration}')
933 chars
33 lines

In this code, we first define the API_KEY and create a googlemaps.Client object. We then define the origin, destination, and waypoints parameters for the route, along with the other parameters required by the API. Finally, we call the directions() method of the client object to get the directions and extract the distance and duration of the route.

gistlibby LogSnag