0
# Geolocation and Static Maps
1
2
Determine device location from radio signals and generate static map images with custom markers, paths, and styling for applications requiring location services and map visualization.
3
4
## Capabilities
5
6
### Device Geolocation
7
8
Determine device location using cellular towers and WiFi access points for location-based services.
9
10
```python { .api }
11
def geolocate(client, home_mobile_country_code=None, home_mobile_network_code=None,
12
radio_type=None, carrier=None, consider_ip=None, cell_towers=None,
13
wifi_access_points=None):
14
"""
15
Determine device location from radio signals.
16
17
Args:
18
client (Client): Google Maps API client instance
19
home_mobile_country_code (int): Mobile country code for home network
20
home_mobile_network_code (int): Mobile network code for home network
21
radio_type (str): Radio type - "gsm", "cdma", "wcdma", "lte"
22
carrier (str): Carrier name
23
consider_ip (bool): Whether to use IP address for fallback location
24
cell_towers (list): List of cell tower dictionaries with signal information
25
wifi_access_points (list): List of WiFi access point dictionaries
26
27
Returns:
28
dict: Geolocation response containing:
29
- location: Estimated location coordinates (lat, lng)
30
- accuracy: Location accuracy radius in meters
31
32
Raises:
33
googlemaps.exceptions.ApiError: When API returns an error
34
googlemaps.exceptions.TransportError: When HTTP request fails
35
googlemaps.exceptions.Timeout: When request times out
36
"""
37
```
38
39
### Static Map Generation
40
41
Generate static map images with markers, paths, and custom styling for embedding in applications.
42
43
```python { .api }
44
def static_map(client, size, center=None, zoom=None, scale=None, format=None,
45
maptype=None, language=None, region=None, markers=None,
46
path=None, visible=None, style=None):
47
"""
48
Generate static map image URL.
49
50
Args:
51
client (Client): Google Maps API client instance
52
size (tuple): Image size as (width, height) tuple. Max 640x640 for free tier.
53
center (tuple): Map center as (lat, lng) coordinates
54
zoom (int): Zoom level (0-21, where 21 is highest detail)
55
scale (int): Image scale factor (1 or 2 for high-DPI displays)
56
format (str): Image format - "png", "png8", "png32", "gif", "jpg", "jpg-baseline"
57
maptype (str): Map type - "roadmap", "satellite", "terrain", "hybrid"
58
language (str): Language for map labels (ISO 639-1)
59
region (str): Region for map features (ISO 3166-1 Alpha-2)
60
markers (list): List of marker specifications or StaticMapMarker objects
61
path (list): List of path specifications or StaticMapPath objects
62
visible (list): Locations to ensure are visible on map
63
style (list): Custom map styling rules
64
65
Returns:
66
str: URL for the generated static map image
67
68
Raises:
69
googlemaps.exceptions.ApiError: When API returns an error
70
googlemaps.exceptions.TransportError: When HTTP request fails
71
googlemaps.exceptions.Timeout: When request times out
72
"""
73
```
74
75
### Map Parameter Classes
76
77
Helper classes for building complex map markers and paths.
78
79
```python { .api }
80
class StaticMapMarker:
81
"""Helper class for building marker parameters."""
82
def __init__(self, locations, size=None, color=None, label=None):
83
"""
84
Args:
85
locations (list): List of marker locations
86
size (str): Marker size - "tiny", "mid", "small"
87
color (str): Marker color name or hex value
88
label (str): Single character label (A-Z, 0-9)
89
"""
90
91
class StaticMapPath:
92
"""Helper class for building path parameters."""
93
def __init__(self, points, weight=None, color=None, fillcolor=None, geodesic=None):
94
"""
95
Args:
96
points (list): List of path coordinates
97
weight (int): Path line weight in pixels
98
color (str): Path color name or hex value
99
fillcolor (str): Fill color for enclosed paths
100
geodesic (bool): Whether to draw geodesic lines
101
"""
102
```
103
104
## Constants
105
106
Supported map formats and types:
107
108
```python { .api }
109
MAPS_IMAGE_FORMATS = {
110
'png8', 'png', 'png32', 'gif', 'jpg', 'jpg-baseline'
111
}
112
113
MAPS_MAP_TYPES = {
114
'roadmap', 'satellite', 'terrain', 'hybrid'
115
}
116
```
117
118
## Usage Examples
119
120
### Basic Geolocation from WiFi
121
122
```python
123
import googlemaps
124
125
gmaps = googlemaps.Client(key='YOUR_API_KEY')
126
127
# Example WiFi access points (you would get these from device scanning)
128
wifi_access_points = [
129
{
130
'macAddress': '00:25:9c:cf:1c:ac',
131
'signalStrength': -43,
132
'channel': 11
133
},
134
{
135
'macAddress': '00:25:9c:cf:1c:ad',
136
'signalStrength': -55,
137
'channel': 6
138
}
139
]
140
141
# Geolocate using WiFi signals
142
location_result = gmaps.geolocate(
143
consider_ip=True,
144
wifi_access_points=wifi_access_points
145
)
146
147
if 'location' in location_result:
148
lat = location_result['location']['lat']
149
lng = location_result['location']['lng']
150
accuracy = location_result['accuracy']
151
152
print(f"Estimated location: ({lat:.6f}, {lng:.6f})")
153
print(f"Accuracy: ±{accuracy} meters")
154
else:
155
print("Location could not be determined")
156
```
157
158
### Geolocation from Cell Towers
159
160
```python
161
import googlemaps
162
163
gmaps = googlemaps.Client(key='YOUR_API_KEY')
164
165
# Example cell tower data (from device radio info)
166
cell_towers = [
167
{
168
'cellId': 42,
169
'locationAreaCode': 415,
170
'mobileCountryCode': 310,
171
'mobileNetworkCode': 410,
172
'signalStrength': -60
173
}
174
]
175
176
# Geolocate using cellular data
177
cellular_location = gmaps.geolocate(
178
radio_type='gsm',
179
carrier='Verizon',
180
consider_ip=False,
181
cell_towers=cell_towers
182
)
183
184
if 'location' in cellular_location:
185
print(f"Cellular location: {cellular_location['location']}")
186
print(f"Accuracy: {cellular_location['accuracy']} meters")
187
```
188
189
### Combined WiFi and Cellular Geolocation
190
191
```python
192
import googlemaps
193
194
gmaps = googlemaps.Client(key='YOUR_API_KEY')
195
196
# Combined data sources for better accuracy
197
combined_location = gmaps.geolocate(
198
home_mobile_country_code=310,
199
home_mobile_network_code=410,
200
radio_type='lte',
201
carrier='T-Mobile',
202
consider_ip=True,
203
cell_towers=[
204
{
205
'cellId': 123,
206
'locationAreaCode': 456,
207
'mobileCountryCode': 310,
208
'mobileNetworkCode': 260,
209
'signalStrength': -65
210
}
211
],
212
wifi_access_points=[
213
{
214
'macAddress': 'aa:bb:cc:dd:ee:ff',
215
'signalStrength': -45,
216
'channel': 1
217
},
218
{
219
'macAddress': '11:22:33:44:55:66',
220
'signalStrength': -70,
221
'channel': 11
222
}
223
]
224
)
225
226
print("Combined geolocation result:")
227
if 'location' in combined_location:
228
print(f"Location: {combined_location['location']}")
229
print(f"Accuracy: {combined_location['accuracy']} meters")
230
```
231
232
### Basic Static Map
233
234
```python
235
import googlemaps
236
237
gmaps = googlemaps.Client(key='YOUR_API_KEY')
238
239
# Generate a simple static map
240
map_url = gmaps.static_map(
241
size=(400, 400),
242
center=(37.7749, -122.4194), # San Francisco
243
zoom=12,
244
maptype='roadmap',
245
format='png'
246
)
247
248
print(f"Static map URL: {map_url}")
249
250
# You can now use this URL in HTML img tags or download the image
251
# <img src="{map_url}" alt="Static Map">
252
```
253
254
### Static Map with Markers
255
256
```python
257
import googlemaps
258
259
gmaps = googlemaps.Client(key='YOUR_API_KEY')
260
261
# Create map with multiple markers
262
markers = [
263
{
264
'location': (37.7749, -122.4194),
265
'color': 'red',
266
'label': 'A'
267
},
268
{
269
'location': (37.7849, -122.4094),
270
'color': 'blue',
271
'label': 'B'
272
}
273
]
274
275
map_with_markers = gmaps.static_map(
276
size=(600, 400),
277
zoom=13,
278
markers=markers,
279
maptype='terrain'
280
)
281
282
print(f"Map with markers: {map_with_markers}")
283
```
284
285
### Static Map with Custom Markers
286
287
```python
288
import googlemaps
289
290
gmaps = googlemaps.Client(key='YOUR_API_KEY')
291
292
# Use StaticMapMarker helper class
293
from googlemaps.maps import StaticMapMarker
294
295
# Create custom markers
296
custom_markers = [
297
StaticMapMarker(
298
locations=[(40.7128, -74.0060)], # NYC
299
size='mid',
300
color='green',
301
label='NYC'
302
),
303
StaticMapMarker(
304
locations=[(34.0522, -118.2437)], # LA
305
size='mid',
306
color='purple',
307
label='LA'
308
)
309
]
310
311
# Create map showing both cities
312
usa_map = gmaps.static_map(
313
size=(640, 400),
314
markers=custom_markers,
315
maptype='roadmap'
316
# Center and zoom will be automatically determined to fit all markers
317
)
318
319
print(f"USA cities map: {usa_map}")
320
```
321
322
### Static Map with Paths
323
324
```python
325
import googlemaps
326
327
gmaps = googlemaps.Client(key='YOUR_API_KEY')
328
329
from googlemaps.maps import StaticMapPath
330
331
# Define a route path
332
route_points = [
333
(37.7749, -122.4194), # San Francisco
334
(37.7849, -122.4094),
335
(37.7949, -122.3994),
336
(37.8049, -122.3894)
337
]
338
339
# Create path specification
340
route_path = StaticMapPath(
341
points=route_points,
342
weight=5,
343
color='blue',
344
geodesic=True
345
)
346
347
# Add markers for start and end
348
markers = [
349
{'location': route_points[0], 'color': 'green', 'label': 'S'},
350
{'location': route_points[-1], 'color': 'red', 'label': 'E'}
351
]
352
353
# Generate map with path and markers
354
route_map = gmaps.static_map(
355
size=(500, 500),
356
path=[route_path],
357
markers=markers,
358
maptype='roadmap'
359
)
360
361
print(f"Route map: {route_map}")
362
```
363
364
### Advanced Static Map with Styling
365
366
```python
367
import googlemaps
368
369
gmaps = googlemaps.Client(key='YOUR_API_KEY')
370
371
# Custom map styling (simplified example)
372
map_styles = [
373
{
374
'feature': 'water',
375
'elementType': 'all',
376
'stylers': [{'color': '#46bcec'}, {'visibility': 'on'}]
377
},
378
{
379
'feature': 'landscape',
380
'elementType': 'all',
381
'stylers': [{'color': '#f2f2f2'}]
382
}
383
]
384
385
# Create styled map
386
styled_map = gmaps.static_map(
387
size=(600, 400),
388
center=(40.7128, -74.0060), # NYC
389
zoom=11,
390
maptype='roadmap',
391
style=map_styles,
392
format='png32' # High quality PNG
393
)
394
395
print(f"Styled map: {styled_map}")
396
```
397
398
### High-Resolution Static Map
399
400
```python
401
import googlemaps
402
403
gmaps = googlemaps.Client(key='YOUR_API_KEY')
404
405
# Generate high-DPI map for retina displays
406
high_res_map = gmaps.static_map(
407
size=(320, 240), # Logical size
408
scale=2, # 2x scale for retina (actual size 640x480)
409
center=(51.5074, -0.1278), # London
410
zoom=10,
411
maptype='satellite',
412
format='jpg'
413
)
414
415
print(f"High-resolution map: {high_res_map}")
416
```
417
418
### Static Map for Specific Locations
419
420
```python
421
import googlemaps
422
423
gmaps = googlemaps.Client(key='YOUR_API_KEY')
424
425
def create_location_map(addresses, title="Locations"):
426
"""Create a static map showing multiple addresses."""
427
428
# Geocode addresses to get coordinates
429
locations = []
430
markers = []
431
432
for i, address in enumerate(addresses):
433
geocode_result = gmaps.geocode(address)
434
if geocode_result:
435
location = geocode_result[0]['geometry']['location']
436
lat_lng = (location['lat'], location['lng'])
437
locations.append(lat_lng)
438
439
# Create marker with letter label
440
markers.append({
441
'location': lat_lng,
442
'color': 'red',
443
'label': chr(65 + i) # A, B, C, etc.
444
})
445
446
if not locations:
447
return None
448
449
# Generate map
450
map_url = gmaps.static_map(
451
size=(640, 480),
452
markers=markers,
453
maptype='roadmap',
454
format='png'
455
)
456
457
return map_url
458
459
# Example usage
460
restaurants = [
461
"Fisherman's Wharf, San Francisco, CA",
462
"Union Square, San Francisco, CA",
463
"Golden Gate Park, San Francisco, CA"
464
]
465
466
restaurant_map = create_location_map(restaurants, "SF Restaurants")
467
if restaurant_map:
468
print(f"Restaurant map: {restaurant_map}")
469
```
470
471
### Download and Save Static Map
472
473
```python
474
import googlemaps
475
import requests
476
477
gmaps = googlemaps.Client(key='YOUR_API_KEY')
478
479
# Generate map URL
480
map_url = gmaps.static_map(
481
size=(800, 600),
482
center=(48.8566, 2.3522), # Paris
483
zoom=12,
484
markers=[{
485
'location': (48.8584, 2.2945), # Eiffel Tower
486
'color': 'red',
487
'size': 'mid',
488
'label': 'E'
489
}],
490
maptype='hybrid'
491
)
492
493
# Download the image
494
response = requests.get(map_url)
495
if response.status_code == 200:
496
with open('paris_map.png', 'wb') as f:
497
f.write(response.content)
498
print("Map saved as paris_map.png")
499
else:
500
print(f"Failed to download map: {response.status_code}")
501
```