Python client library for Google Maps Platform providing access to mapping services, geocoding, routing, and location APIs
—
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.
Determine device location using cellular towers and WiFi access points for location-based services.
def geolocate(client, home_mobile_country_code=None, home_mobile_network_code=None,
radio_type=None, carrier=None, consider_ip=None, cell_towers=None,
wifi_access_points=None):
"""
Determine device location from radio signals.
Args:
client (Client): Google Maps API client instance
home_mobile_country_code (int): Mobile country code for home network
home_mobile_network_code (int): Mobile network code for home network
radio_type (str): Radio type - "gsm", "cdma", "wcdma", "lte"
carrier (str): Carrier name
consider_ip (bool): Whether to use IP address for fallback location
cell_towers (list): List of cell tower dictionaries with signal information
wifi_access_points (list): List of WiFi access point dictionaries
Returns:
dict: Geolocation response containing:
- location: Estimated location coordinates (lat, lng)
- accuracy: Location accuracy radius in meters
Raises:
googlemaps.exceptions.ApiError: When API returns an error
googlemaps.exceptions.TransportError: When HTTP request fails
googlemaps.exceptions.Timeout: When request times out
"""Generate static map images with markers, paths, and custom styling for embedding in applications.
def static_map(client, size, center=None, zoom=None, scale=None, format=None,
maptype=None, language=None, region=None, markers=None,
path=None, visible=None, style=None):
"""
Generate static map image URL.
Args:
client (Client): Google Maps API client instance
size (tuple): Image size as (width, height) tuple. Max 640x640 for free tier.
center (tuple): Map center as (lat, lng) coordinates
zoom (int): Zoom level (0-21, where 21 is highest detail)
scale (int): Image scale factor (1 or 2 for high-DPI displays)
format (str): Image format - "png", "png8", "png32", "gif", "jpg", "jpg-baseline"
maptype (str): Map type - "roadmap", "satellite", "terrain", "hybrid"
language (str): Language for map labels (ISO 639-1)
region (str): Region for map features (ISO 3166-1 Alpha-2)
markers (list): List of marker specifications or StaticMapMarker objects
path (list): List of path specifications or StaticMapPath objects
visible (list): Locations to ensure are visible on map
style (list): Custom map styling rules
Returns:
str: URL for the generated static map image
Raises:
googlemaps.exceptions.ApiError: When API returns an error
googlemaps.exceptions.TransportError: When HTTP request fails
googlemaps.exceptions.Timeout: When request times out
"""Helper classes for building complex map markers and paths.
class StaticMapMarker:
"""Helper class for building marker parameters."""
def __init__(self, locations, size=None, color=None, label=None):
"""
Args:
locations (list): List of marker locations
size (str): Marker size - "tiny", "mid", "small"
color (str): Marker color name or hex value
label (str): Single character label (A-Z, 0-9)
"""
class StaticMapPath:
"""Helper class for building path parameters."""
def __init__(self, points, weight=None, color=None, fillcolor=None, geodesic=None):
"""
Args:
points (list): List of path coordinates
weight (int): Path line weight in pixels
color (str): Path color name or hex value
fillcolor (str): Fill color for enclosed paths
geodesic (bool): Whether to draw geodesic lines
"""Supported map formats and types:
MAPS_IMAGE_FORMATS = {
'png8', 'png', 'png32', 'gif', 'jpg', 'jpg-baseline'
}
MAPS_MAP_TYPES = {
'roadmap', 'satellite', 'terrain', 'hybrid'
}import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Example WiFi access points (you would get these from device scanning)
wifi_access_points = [
{
'macAddress': '00:25:9c:cf:1c:ac',
'signalStrength': -43,
'channel': 11
},
{
'macAddress': '00:25:9c:cf:1c:ad',
'signalStrength': -55,
'channel': 6
}
]
# Geolocate using WiFi signals
location_result = gmaps.geolocate(
consider_ip=True,
wifi_access_points=wifi_access_points
)
if 'location' in location_result:
lat = location_result['location']['lat']
lng = location_result['location']['lng']
accuracy = location_result['accuracy']
print(f"Estimated location: ({lat:.6f}, {lng:.6f})")
print(f"Accuracy: ±{accuracy} meters")
else:
print("Location could not be determined")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Example cell tower data (from device radio info)
cell_towers = [
{
'cellId': 42,
'locationAreaCode': 415,
'mobileCountryCode': 310,
'mobileNetworkCode': 410,
'signalStrength': -60
}
]
# Geolocate using cellular data
cellular_location = gmaps.geolocate(
radio_type='gsm',
carrier='Verizon',
consider_ip=False,
cell_towers=cell_towers
)
if 'location' in cellular_location:
print(f"Cellular location: {cellular_location['location']}")
print(f"Accuracy: {cellular_location['accuracy']} meters")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Combined data sources for better accuracy
combined_location = gmaps.geolocate(
home_mobile_country_code=310,
home_mobile_network_code=410,
radio_type='lte',
carrier='T-Mobile',
consider_ip=True,
cell_towers=[
{
'cellId': 123,
'locationAreaCode': 456,
'mobileCountryCode': 310,
'mobileNetworkCode': 260,
'signalStrength': -65
}
],
wifi_access_points=[
{
'macAddress': 'aa:bb:cc:dd:ee:ff',
'signalStrength': -45,
'channel': 1
},
{
'macAddress': '11:22:33:44:55:66',
'signalStrength': -70,
'channel': 11
}
]
)
print("Combined geolocation result:")
if 'location' in combined_location:
print(f"Location: {combined_location['location']}")
print(f"Accuracy: {combined_location['accuracy']} meters")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Generate a simple static map
map_url = gmaps.static_map(
size=(400, 400),
center=(37.7749, -122.4194), # San Francisco
zoom=12,
maptype='roadmap',
format='png'
)
print(f"Static map URL: {map_url}")
# You can now use this URL in HTML img tags or download the image
# <img src="{map_url}" alt="Static Map">import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Create map with multiple markers
markers = [
{
'location': (37.7749, -122.4194),
'color': 'red',
'label': 'A'
},
{
'location': (37.7849, -122.4094),
'color': 'blue',
'label': 'B'
}
]
map_with_markers = gmaps.static_map(
size=(600, 400),
zoom=13,
markers=markers,
maptype='terrain'
)
print(f"Map with markers: {map_with_markers}")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Use StaticMapMarker helper class
from googlemaps.maps import StaticMapMarker
# Create custom markers
custom_markers = [
StaticMapMarker(
locations=[(40.7128, -74.0060)], # NYC
size='mid',
color='green',
label='NYC'
),
StaticMapMarker(
locations=[(34.0522, -118.2437)], # LA
size='mid',
color='purple',
label='LA'
)
]
# Create map showing both cities
usa_map = gmaps.static_map(
size=(640, 400),
markers=custom_markers,
maptype='roadmap'
# Center and zoom will be automatically determined to fit all markers
)
print(f"USA cities map: {usa_map}")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
from googlemaps.maps import StaticMapPath
# Define a route path
route_points = [
(37.7749, -122.4194), # San Francisco
(37.7849, -122.4094),
(37.7949, -122.3994),
(37.8049, -122.3894)
]
# Create path specification
route_path = StaticMapPath(
points=route_points,
weight=5,
color='blue',
geodesic=True
)
# Add markers for start and end
markers = [
{'location': route_points[0], 'color': 'green', 'label': 'S'},
{'location': route_points[-1], 'color': 'red', 'label': 'E'}
]
# Generate map with path and markers
route_map = gmaps.static_map(
size=(500, 500),
path=[route_path],
markers=markers,
maptype='roadmap'
)
print(f"Route map: {route_map}")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Custom map styling (simplified example)
map_styles = [
{
'feature': 'water',
'elementType': 'all',
'stylers': [{'color': '#46bcec'}, {'visibility': 'on'}]
},
{
'feature': 'landscape',
'elementType': 'all',
'stylers': [{'color': '#f2f2f2'}]
}
]
# Create styled map
styled_map = gmaps.static_map(
size=(600, 400),
center=(40.7128, -74.0060), # NYC
zoom=11,
maptype='roadmap',
style=map_styles,
format='png32' # High quality PNG
)
print(f"Styled map: {styled_map}")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Generate high-DPI map for retina displays
high_res_map = gmaps.static_map(
size=(320, 240), # Logical size
scale=2, # 2x scale for retina (actual size 640x480)
center=(51.5074, -0.1278), # London
zoom=10,
maptype='satellite',
format='jpg'
)
print(f"High-resolution map: {high_res_map}")import googlemaps
gmaps = googlemaps.Client(key='YOUR_API_KEY')
def create_location_map(addresses, title="Locations"):
"""Create a static map showing multiple addresses."""
# Geocode addresses to get coordinates
locations = []
markers = []
for i, address in enumerate(addresses):
geocode_result = gmaps.geocode(address)
if geocode_result:
location = geocode_result[0]['geometry']['location']
lat_lng = (location['lat'], location['lng'])
locations.append(lat_lng)
# Create marker with letter label
markers.append({
'location': lat_lng,
'color': 'red',
'label': chr(65 + i) # A, B, C, etc.
})
if not locations:
return None
# Generate map
map_url = gmaps.static_map(
size=(640, 480),
markers=markers,
maptype='roadmap',
format='png'
)
return map_url
# Example usage
restaurants = [
"Fisherman's Wharf, San Francisco, CA",
"Union Square, San Francisco, CA",
"Golden Gate Park, San Francisco, CA"
]
restaurant_map = create_location_map(restaurants, "SF Restaurants")
if restaurant_map:
print(f"Restaurant map: {restaurant_map}")import googlemaps
import requests
gmaps = googlemaps.Client(key='YOUR_API_KEY')
# Generate map URL
map_url = gmaps.static_map(
size=(800, 600),
center=(48.8566, 2.3522), # Paris
zoom=12,
markers=[{
'location': (48.8584, 2.2945), # Eiffel Tower
'color': 'red',
'size': 'mid',
'label': 'E'
}],
maptype='hybrid'
)
# Download the image
response = requests.get(map_url)
if response.status_code == 200:
with open('paris_map.png', 'wb') as f:
f.write(response.content)
print("Map saved as paris_map.png")
else:
print(f"Failed to download map: {response.status_code}")Install with Tessl CLI
npx tessl i tessl/pypi-googlemaps