CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-googlemaps

Python client library for Google Maps Platform providing access to mapping services, geocoding, routing, and location APIs

Pending
Overview
Eval results
Files

routing.mddocs/

Routing and Directions

Calculate routes, travel times, and distances between locations with support for multiple transportation modes, waypoint optimization, traffic data, and transit options.

Capabilities

Route Directions

Get step-by-step directions between locations with support for waypoints, alternative routes, and various transportation modes.

def directions(client, origin, destination, mode=None, waypoints=None,
              alternatives=False, avoid=None, language=None, units=None,
              region=None, departure_time=None, arrival_time=None,
              optimize_waypoints=False, transit_mode=None,
              transit_routing_preference=None, traffic_model=None):
    """
    Get routing directions between locations.
    
    Args:
        client (Client): Google Maps API client instance
        origin (str): Starting address, place ID, or lat/lng coordinates
        destination (str): Ending address, place ID, or lat/lng coordinates
        mode (str): Transportation mode - "driving", "walking", "bicycling", "transit"
        waypoints (list): Intermediate stops as addresses or coordinates
        alternatives (bool): Whether to return alternative routes
        avoid (list): Route restrictions - ["tolls", "highways", "ferries", "indoor"]
        language (str): Language code for returned text (ISO 639-1)
        units (str): Unit system - "metric" or "imperial"
        region (str): Region code for result biasing (ISO 3166-1 Alpha-2)
        departure_time (datetime): Departure time for transit/traffic
        arrival_time (datetime): Desired arrival time for transit
        optimize_waypoints (bool): Whether to optimize waypoint order
        transit_mode (list): Transit types - ["bus", "subway", "train", "tram", "rail"]
        transit_routing_preference (str): Transit preference - "less_walking", "fewer_transfers"
        traffic_model (str): Traffic model - "best_guess", "pessimistic", "optimistic"
    
    Returns:
        list: List of route dictionaries containing legs, steps, duration,
              distance, polyline, and bounds information
    
    Raises:
        googlemaps.exceptions.ApiError: When API returns an error
        googlemaps.exceptions.TransportError: When HTTP request fails
        googlemaps.exceptions.Timeout: When request times out
    """

Distance Matrix

Calculate travel distances and times between multiple origins and destinations for route optimization and planning.

def distance_matrix(client, origins, destinations, mode=None, language=None,
                   avoid=None, units=None, departure_time=None,
                   arrival_time=None, transit_mode=None,
                   transit_routing_preference=None, traffic_model=None,
                   region=None):
    """
    Calculate distances and times between multiple origins and destinations.
    
    Args:
        client (Client): Google Maps API client instance
        origins (list): List of starting locations (addresses or coordinates)
        destinations (list): List of ending locations (addresses or coordinates)
        mode (str): Transportation mode - "driving", "walking", "bicycling", "transit"
        language (str): Language code for returned text (ISO 639-1)
        avoid (list): Route restrictions - ["tolls", "highways", "ferries", "indoor"]
        units (str): Unit system - "metric" or "imperial"
        departure_time (datetime): Departure time for transit/traffic calculations
        arrival_time (datetime): Desired arrival time for transit
        transit_mode (list): Transit types - ["bus", "subway", "train", "tram", "rail"]
        transit_routing_preference (str): Transit preference - "less_walking", "fewer_transfers"
        traffic_model (str): Traffic model - "best_guess", "pessimistic", "optimistic"
        region (str): Region code for result biasing (ISO 3166-1 Alpha-2)
    
    Returns:
        dict: Matrix with origin/destination addresses and elements containing
              distance, duration, and status for each origin-destination pair
    
    Raises:
        googlemaps.exceptions.ApiError: When API returns an error
        googlemaps.exceptions.TransportError: When HTTP request fails
        googlemaps.exceptions.Timeout: When request times out
    """

Usage Examples

Basic Driving Directions

import googlemaps
from datetime import datetime

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get driving directions
directions_result = gmaps.directions(
    origin="Sydney Town Hall",
    destination="Parramatta, NSW",
    mode="driving"
)

# Extract route information
route = directions_result[0]
duration = route['legs'][0]['duration']['text']
distance = route['legs'][0]['distance']['text']
print(f"Duration: {duration}, Distance: {distance}")

# Get step-by-step instructions
for step in route['legs'][0]['steps']:
    instruction = step['html_instructions']
    step_distance = step['distance']['text']
    print(f"- {instruction} ({step_distance})")

Transit Directions with Real-Time

import googlemaps
from datetime import datetime, timedelta

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get transit directions with departure time
departure_time = datetime.now() + timedelta(minutes=30)

transit_result = gmaps.directions(
    origin="Union Station, Los Angeles",
    destination="Santa Monica Pier",
    mode="transit",
    departure_time=departure_time,
    transit_mode=["subway", "bus"],
    transit_routing_preference="fewer_transfers"
)

# Extract transit details
route = transit_result[0]
for leg in route['legs']:
    for step in leg['steps']:
        if step['travel_mode'] == 'TRANSIT':
            transit_details = step['transit_details']
            line = transit_details['line']['short_name']
            departure_stop = transit_details['departure_stop']['name']
            arrival_stop = transit_details['arrival_stop']['name']
            print(f"Take {line} from {departure_stop} to {arrival_stop}")

Multi-Waypoint Route with Optimization

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Route with multiple waypoints
waypoints = [
    "Statue of Liberty, NY",
    "Empire State Building, NY",
    "Central Park, NY"
]

optimized_route = gmaps.directions(
    origin="Times Square, NY",
    destination="Brooklyn Bridge, NY",
    waypoints=waypoints,
    optimize_waypoints=True,
    mode="driving"
)

# Check optimized waypoint order
waypoint_order = optimized_route[0]['waypoint_order']
print("Optimized waypoint order:", waypoint_order)

# Get total route duration and distance
total_duration = 0
total_distance = 0
for leg in optimized_route[0]['legs']:
    total_duration += leg['duration']['value']
    total_distance += leg['distance']['value']

print(f"Total time: {total_duration // 60} minutes")
print(f"Total distance: {total_distance / 1000:.1f} km")

Alternative Routes with Restrictions

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get alternative routes avoiding tolls and highways
alternatives_result = gmaps.directions(
    origin="San Francisco, CA",
    destination="Los Angeles, CA",
    mode="driving",
    alternatives=True,
    avoid=["tolls", "highways"],
    units="imperial"
)

# Compare alternative routes
for i, route in enumerate(alternatives_result):
    duration = route['legs'][0]['duration']['text']
    distance = route['legs'][0]['distance']['text']
    print(f"Route {i+1}: {duration}, {distance}")

Traffic-Aware Routing

import googlemaps
from datetime import datetime

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get directions with traffic considerations
rush_hour = datetime(2024, 1, 15, 8, 30)  # Monday 8:30 AM

traffic_route = gmaps.directions(
    origin="Downtown LA",
    destination="LAX Airport",
    mode="driving",
    departure_time=rush_hour,
    traffic_model="pessimistic"
)

# Compare duration with and without traffic
route = traffic_route[0]
duration_in_traffic = route['legs'][0]['duration_in_traffic']['text']
duration_normal = route['legs'][0]['duration']['text']

print(f"Normal time: {duration_normal}")
print(f"In traffic: {duration_in_traffic}")

Distance Matrix for Multiple Locations

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Calculate distances between multiple points
origins = ["New York, NY", "Boston, MA", "Philadelphia, PA"]
destinations = ["Washington DC", "Baltimore, MD", "Richmond, VA"]

matrix_result = gmaps.distance_matrix(
    origins=origins,
    destinations=destinations,
    mode="driving",
    units="imperial"
)

# Process the matrix results
for i, origin in enumerate(matrix_result['origin_addresses']):
    print(f"\nFrom: {origin}")
    for j, destination in enumerate(matrix_result['destination_addresses']):
        element = matrix_result['rows'][i]['elements'][j]
        if element['status'] == 'OK':
            distance = element['distance']['text']
            duration = element['duration']['text']
            print(f"  To {destination}: {distance}, {duration}")

Walking and Cycling Directions

import googlemaps

gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Walking directions
walking_result = gmaps.directions(
    origin="Central Park, NY",
    destination="Metropolitan Museum, NY",
    mode="walking"
)

walking_duration = walking_result[0]['legs'][0]['duration']['text']
print(f"Walking time: {walking_duration}")

# Cycling directions
cycling_result = gmaps.directions(
    origin="Golden Gate Park, SF",
    destination="Fisherman's Wharf, SF",
    mode="bicycling"
)

cycling_duration = cycling_result[0]['legs'][0]['duration']['text']
print(f"Cycling time: {cycling_duration}")

Route Data Structure

Direction results contain detailed route information:

# Example of accessing route data
route = directions_result[0]

# Route-level information
bounds = route['bounds']            # Geographic bounds
overview_polyline = route['overview_polyline']['points']  # Encoded polyline
warnings = route.get('warnings', [])  # Route warnings

# Leg-level information (between waypoints)
for leg in route['legs']:
    start_address = leg['start_address']
    end_address = leg['end_address']
    distance = leg['distance']      # {'text': '10.2 km', 'value': 10200}
    duration = leg['duration']      # {'text': '15 mins', 'value': 900}
    
    # Step-level information (turn-by-turn)
    for step in leg['steps']:
        instruction = step['html_instructions']
        travel_mode = step['travel_mode']  # DRIVING, WALKING, TRANSIT
        step_distance = step['distance']
        step_duration = step['duration']
        
        # For transit steps
        if 'transit_details' in step:
            transit_info = step['transit_details']
            line_name = transit_info['line']['short_name']
            vehicle_type = transit_info['line']['vehicle']['type']

Install with Tessl CLI

npx tessl i tessl/pypi-googlemaps

docs

address-validation.md

client-config.md

elevation-geography.md

geocoding.md

geolocation-maps.md

index.md

places.md

roads.md

routing.md

tile.json