Python client library for Google Maps Platform providing access to mapping services, geocoding, routing, and location APIs
npx @tessl/cli install tessl/pypi-googlemaps@4.10.0A comprehensive Python client library for Google Maps Platform Web Services, enabling developers to integrate mapping functionality into their applications. It provides convenient Python interfaces for multiple Google Maps APIs including Directions, Distance Matrix, Elevation, Geocoding, Geolocation, Time Zone, Roads, Places, Maps Static, and Address Validation APIs.
pip install googlemapsimport googlemapsCommon usage pattern:
from googlemaps import Clientimport googlemaps
# Initialize the client with your API key
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Geocoding example - convert address to coordinates
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
print(geocode_result[0]['geometry']['location'])
# Reverse geocoding - convert coordinates to address
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))
print(reverse_geocode_result[0]['formatted_address'])
# Get directions between two points
directions_result = gmaps.directions("Sydney Town Hall",
"Parramatta, NSW",
mode="transit",
departure_time=datetime.now())The library is built around a central Client class that handles authentication, rate limiting, error handling, and HTTP requests. All API functions are dynamically attached to the Client class using the make_api_method decorator, enabling both functional and object-oriented usage patterns.
Core client initialization with authentication, rate limiting, timeout configuration, and request customization options.
class Client:
def __init__(self, key=None, client_id=None, client_secret=None,
timeout=None, connect_timeout=None, read_timeout=None,
retry_timeout=60, requests_kwargs=None,
queries_per_second=60, queries_per_minute=6000, channel=None,
retry_over_query_limit=True, experience_id=None,
requests_session=None, base_url="https://maps.googleapis.com"):
"""
Initialize Google Maps API client.
Args:
key (str): API key (required unless using enterprise credentials)
client_id (str): Enterprise client ID
client_secret (str): Enterprise client secret (base64 encoded)
timeout (int): Combined connect/read timeout in seconds
retry_timeout (int): Timeout across retriable requests (default: 60)
queries_per_second (int): QPS rate limit (default: 60)
queries_per_minute (int): QPM rate limit (default: 6000)
"""Convert between addresses and coordinates using Google's geocoding and reverse geocoding APIs with support for component filtering, bounds, and localization.
def geocode(client, address=None, place_id=None, components=None,
bounds=None, region=None, language=None):
"""Convert address to coordinates."""
def reverse_geocode(client, latlng, result_type=None, location_type=None,
language=None):
"""Convert coordinates to address."""Calculate routes, travel times, and distances between locations with support for multiple transportation modes, waypoint optimization, and real-time traffic data.
def directions(client, origin, destination, mode=None, waypoints=None,
alternatives=False, avoid=None, departure_time=None):
"""Get routing directions between locations."""
def distance_matrix(client, origins, destinations, mode=None, language=None,
departure_time=None, traffic_model=None):
"""Calculate distances and times between multiple points."""Search for places, get detailed place information, autocomplete suggestions, and place photos using Google's comprehensive places database.
def find_place(client, input, input_type, fields=None, location_bias=None):
"""Find places by text or phone number."""
def places_nearby(client, location=None, radius=None, type=None):
"""Search for nearby places."""
def places_autocomplete(client, input_text, location=None, radius=None):
"""Get place autocomplete suggestions."""Retrieve elevation data for specific locations or along paths, and access timezone information for any location worldwide.
def elevation(client, locations):
"""Get elevation data for locations."""
def timezone(client, location, timestamp=None, language=None):
"""Get timezone information for location."""Snap GPS coordinates to road networks, find nearest roads, and retrieve speed limit information for navigation and tracking applications.
def snap_to_roads(client, path, interpolate=False):
"""Snap coordinates to road network."""
def speed_limits(client, place_ids):
"""Get speed limits for road segments."""Determine device location from radio signals and generate static map images with custom markers, paths, and styling.
def geolocate(client, cell_towers=None, wifi_access_points=None):
"""Locate device from radio signals."""
def static_map(client, size, center=None, zoom=None, markers=None):
"""Generate static map image URL."""Validate and standardize postal addresses using Google's address validation service with support for USPS CASS certification.
def addressvalidation(client, addressLines, regionCode=None,
enableUspsCass=None):
"""Validate postal addresses."""The library provides a structured exception hierarchy for handling different types of failures:
class ApiError(Exception):
"""API errors from server response."""
def __init__(self, status, message=None): ...
class TransportError(Exception):
"""HTTP transport errors."""
class Timeout(Exception):
"""Request timeout errors."""All API methods can raise these exceptions based on the type of failure encountered.
The library provides utility functions for data format conversion and processing:
# Coordinate and location utilities
def latlng(arg):
"""Convert coordinates to API string format."""
def normalize_lat_lng(arg):
"""Normalize lat/lng to standardized tuple."""
def location_list(locations):
"""Convert location list to pipe-separated string."""
# Time and data formatting
def time(timestamp):
"""Convert datetime to Unix timestamp."""
def components(components_dict):
"""Format geocoding component filters."""
def bounds(bounds_dict):
"""Format bounding box for API requests."""
# Polyline encoding/decoding
def decode_polyline(polyline_str):
"""Decode polyline string to coordinate list."""
def encode_polyline(coordinates):
"""Encode coordinate list to polyline string."""These utilities are automatically used by the API functions but can also be used directly for data processing.