0
# Google Maps Services Python Client
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: googlemaps
7
- **Language**: Python
8
- **Installation**: `pip install googlemaps`
9
10
## Core Imports
11
12
```python
13
import googlemaps
14
```
15
16
Common usage pattern:
17
18
```python
19
from googlemaps import Client
20
```
21
22
## Basic Usage
23
24
```python
25
import googlemaps
26
27
# Initialize the client with your API key
28
gmaps = googlemaps.Client(key='YOUR_API_KEY')
29
30
# Geocoding example - convert address to coordinates
31
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
32
print(geocode_result[0]['geometry']['location'])
33
34
# Reverse geocoding - convert coordinates to address
35
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))
36
print(reverse_geocode_result[0]['formatted_address'])
37
38
# Get directions between two points
39
directions_result = gmaps.directions("Sydney Town Hall",
40
"Parramatta, NSW",
41
mode="transit",
42
departure_time=datetime.now())
43
```
44
45
## Architecture
46
47
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.
48
49
### Key Components
50
51
- **Client**: Central class managing authentication, rate limiting, and request handling with automatic retry logic
52
- **API Modules**: Separate modules for each Google Maps API service (directions, geocoding, places, etc.)
53
- **Conversion Utilities**: Helper functions for transforming Python types to API-compatible formats
54
- **Exception Hierarchy**: Structured error handling for different failure modes
55
56
## Capabilities
57
58
### Client Configuration
59
60
Core client initialization with authentication, rate limiting, timeout configuration, and request customization options.
61
62
```python { .api }
63
class Client:
64
def __init__(self, key=None, client_id=None, client_secret=None,
65
timeout=None, connect_timeout=None, read_timeout=None,
66
retry_timeout=60, requests_kwargs=None,
67
queries_per_second=60, queries_per_minute=6000, channel=None,
68
retry_over_query_limit=True, experience_id=None,
69
requests_session=None, base_url="https://maps.googleapis.com"):
70
"""
71
Initialize Google Maps API client.
72
73
Args:
74
key (str): API key (required unless using enterprise credentials)
75
client_id (str): Enterprise client ID
76
client_secret (str): Enterprise client secret (base64 encoded)
77
timeout (int): Combined connect/read timeout in seconds
78
retry_timeout (int): Timeout across retriable requests (default: 60)
79
queries_per_second (int): QPS rate limit (default: 60)
80
queries_per_minute (int): QPM rate limit (default: 6000)
81
"""
82
```
83
84
[Client Configuration](./client-config.md)
85
86
### Geocoding Services
87
88
Convert between addresses and coordinates using Google's geocoding and reverse geocoding APIs with support for component filtering, bounds, and localization.
89
90
```python { .api }
91
def geocode(client, address=None, place_id=None, components=None,
92
bounds=None, region=None, language=None):
93
"""Convert address to coordinates."""
94
95
def reverse_geocode(client, latlng, result_type=None, location_type=None,
96
language=None):
97
"""Convert coordinates to address."""
98
```
99
100
[Geocoding Services](./geocoding.md)
101
102
### Routing and Directions
103
104
Calculate routes, travel times, and distances between locations with support for multiple transportation modes, waypoint optimization, and real-time traffic data.
105
106
```python { .api }
107
def directions(client, origin, destination, mode=None, waypoints=None,
108
alternatives=False, avoid=None, departure_time=None):
109
"""Get routing directions between locations."""
110
111
def distance_matrix(client, origins, destinations, mode=None, language=None,
112
departure_time=None, traffic_model=None):
113
"""Calculate distances and times between multiple points."""
114
```
115
116
[Routing and Directions](./routing.md)
117
118
### Places API
119
120
Search for places, get detailed place information, autocomplete suggestions, and place photos using Google's comprehensive places database.
121
122
```python { .api }
123
def find_place(client, input, input_type, fields=None, location_bias=None):
124
"""Find places by text or phone number."""
125
126
def places_nearby(client, location=None, radius=None, type=None):
127
"""Search for nearby places."""
128
129
def places_autocomplete(client, input_text, location=None, radius=None):
130
"""Get place autocomplete suggestions."""
131
```
132
133
[Places API](./places.md)
134
135
### Elevation and Geography
136
137
Retrieve elevation data for specific locations or along paths, and access timezone information for any location worldwide.
138
139
```python { .api }
140
def elevation(client, locations):
141
"""Get elevation data for locations."""
142
143
def timezone(client, location, timestamp=None, language=None):
144
"""Get timezone information for location."""
145
```
146
147
[Elevation and Geography](./elevation-geography.md)
148
149
### Roads API
150
151
Snap GPS coordinates to road networks, find nearest roads, and retrieve speed limit information for navigation and tracking applications.
152
153
```python { .api }
154
def snap_to_roads(client, path, interpolate=False):
155
"""Snap coordinates to road network."""
156
157
def speed_limits(client, place_ids):
158
"""Get speed limits for road segments."""
159
```
160
161
[Roads API](./roads.md)
162
163
### Geolocation and Static Maps
164
165
Determine device location from radio signals and generate static map images with custom markers, paths, and styling.
166
167
```python { .api }
168
def geolocate(client, cell_towers=None, wifi_access_points=None):
169
"""Locate device from radio signals."""
170
171
def static_map(client, size, center=None, zoom=None, markers=None):
172
"""Generate static map image URL."""
173
```
174
175
[Geolocation and Static Maps](./geolocation-maps.md)
176
177
### Address Validation
178
179
Validate and standardize postal addresses using Google's address validation service with support for USPS CASS certification.
180
181
```python { .api }
182
def addressvalidation(client, addressLines, regionCode=None,
183
enableUspsCass=None):
184
"""Validate postal addresses."""
185
```
186
187
[Address Validation](./address-validation.md)
188
189
## Error Handling
190
191
The library provides a structured exception hierarchy for handling different types of failures:
192
193
```python { .api }
194
class ApiError(Exception):
195
"""API errors from server response."""
196
def __init__(self, status, message=None): ...
197
198
class TransportError(Exception):
199
"""HTTP transport errors."""
200
201
class Timeout(Exception):
202
"""Request timeout errors."""
203
```
204
205
All API methods can raise these exceptions based on the type of failure encountered.
206
207
## Utility Functions
208
209
The library provides utility functions for data format conversion and processing:
210
211
```python { .api }
212
# Coordinate and location utilities
213
def latlng(arg):
214
"""Convert coordinates to API string format."""
215
216
def normalize_lat_lng(arg):
217
"""Normalize lat/lng to standardized tuple."""
218
219
def location_list(locations):
220
"""Convert location list to pipe-separated string."""
221
222
# Time and data formatting
223
def time(timestamp):
224
"""Convert datetime to Unix timestamp."""
225
226
def components(components_dict):
227
"""Format geocoding component filters."""
228
229
def bounds(bounds_dict):
230
"""Format bounding box for API requests."""
231
232
# Polyline encoding/decoding
233
def decode_polyline(polyline_str):
234
"""Decode polyline string to coordinate list."""
235
236
def encode_polyline(coordinates):
237
"""Encode coordinate list to polyline string."""
238
```
239
240
These utilities are automatically used by the API functions but can also be used directly for data processing.