Skip to content

Static Maps

StaticMap

StaticMap()

Google Static Maps URL builder.

Purpose

Builds static map URLs for markers, paths, and geographic bounding boxes.

Attributes:

Name Type Description
api_key Optional[str]

Google Maps credential attached to static URLs.

zoom Optional[int]

Zoom level for the current static map.

size Optional[str]

Map image dimensions in pixels.

latitude Optional[float]

Latitude of the current marker.

longitude Optional[float]

Longitude of the current marker.

params Optional[Dict]

Current Static Maps query parameters.

markers Optional[str]

Encoded marker coordinates.

base_url Optional[str]

Static Maps HTTP endpoint.

points Optional[list]

Coordinates used for markers or path geometry.

maptype Optional[str]

Selected static map layer type.

color Optional[str]

Marker or path color.

weight Optional[int]

Path line weight.

west Optional[float]

Western bounding longitude.

south Optional[float]

Southern bounding latitude.

east Optional[float]

Eastern bounding longitude.

north Optional[float]

Northern bounding latitude.

Initialize Google Static Maps URL configuration and output state.

Purpose

Initialize Google Static Maps URL configuration and output state.

Returns:

Name Type Description
None None

Initializes instance state.

Source code in mapping.py
def __init__( self ) -> None:
	"""Initialize Google Static Maps URL configuration and output state.

	Purpose:
		Initialize Google Static Maps URL configuration and output state.

	Returns:
		None: Initializes instance state.
	"""
	self.api_key = cfg.GOOGLEMAPS_API_KEY
	self.zoom = None
	self.size = None
	self.latitude = None
	self.longitude = None
	self.params = None
	self.markers = None
	self.base_url = 'https://maps.googleapis.com/maps/api/staticmap'
	self.points = None
	self.maptype = None
	self.color = None
	self.weight = None
	self.west = None
	self.south = None
	self.east = None
	self.north = None

Methods:

validate_coordinate

validate_coordinate(lat: float, lng: float) -> tuple
Purpose

Validate and normalize a latitude and longitude pair.

Parameters:

Name Type Description Default
lat float

Latitude in decimal degrees.

required
lng float

Longitude in decimal degrees.

required

Returns:

Name Type Description
tuple tuple

Validated latitude and longitude.

Source code in mapping.py
def validate_coordinate( self, lat: float, lng: float ) -> tuple:
	"""

		Purpose:
			Validate and normalize a latitude and longitude pair.

		Args:
			lat (float):
				Latitude in decimal degrees.

			lng (float):
				Longitude in decimal degrees.

		Returns:
			tuple:
				Validated latitude and longitude.
	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		latitude = float( lat )
		longitude = float( lng )
		if latitude < -90.0 or latitude > 90.0:
			raise ValueError( 'Latitude must be between -90 and 90.' )
		if longitude < -180.0 or longitude > 180.0:
			raise ValueError( 'Longitude must be between -180 and 180.' )
		self.latitude = latitude
		self.longitude = longitude
		return self.latitude, self.longitude
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = "validate_coordinate( self, lat: float, lng: float ) -> tuple"
		Logger( ).write( exception )
		raise exception

normalize_points

normalize_points(points: list) -> list
Purpose

Normalize coordinate tuples, coordinate lists, or dictionaries with lat/lng fields into validated coordinate tuples.

Parameters:

Name Type Description Default
points list

List of coordinates. Supported item shapes include: (lat, lng), [lat, lng], {'lat': value, 'lng': value}, and {'latitude': value, 'longitude': value}.

required

Returns:

Name Type Description
list list

List of validated coordinate tuples.

Source code in mapping.py
def normalize_points( self, points: list ) -> list:
	"""

		Purpose:
			Normalize coordinate tuples, coordinate lists, or dictionaries with
			lat/lng fields into validated coordinate tuples.

		Args:
			points (list):
				List of coordinates. Supported item shapes include:
				(lat, lng), [lat, lng], {'lat': value, 'lng': value}, and
				{'latitude': value, 'longitude': value}.

		Returns:
			list:
				List of validated coordinate tuples.

	"""
	try:
		throw_if( 'points', points )
		if not isinstance( points, list ):
			raise ValueError( 'points must be a list.' )
		output = [ ]
		for point in points:
			if isinstance( point, dict ):
				lat_value = point.get( 'lat', point.get( 'latitude' ) )
				lng_value = point.get( 'lng', point.get( 'longitude' ) )
				output.append( self.validate_coordinate( lat_value, lng_value ) )
			elif isinstance( point, tuple ) and len( point ) == 2:
				output.append( self.validate_coordinate( point[ 0 ], point[ 1 ] ) )
			elif isinstance( point, list ) and len( point ) == 2:
				output.append( self.validate_coordinate( point[ 0 ], point[ 1 ] ) )
			else:
				raise ValueError( f'Unsupported point format: {point}' )
		if not output:
			raise ValueError( 'At least one coordinate is required.' )
		self.points = output
		return self.points
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = "normalize_points( self, points: list ) -> list"
		Logger( ).write( exception )
		raise exception

build_url

build_url(params: Dict) -> str | None
Purpose

Build a Google Static Maps URL from a parameter dictionary.

Parameters:

Name Type Description Default
params Dict

Google Static Maps query parameters.

required

Returns:

Type Description
str | None

str | None: Fully-qualified Google Static Maps URL.

Source code in mapping.py
def build_url( self, params: Dict ) -> str | None:
	"""

		Purpose:
			Build a Google Static Maps URL from a parameter dictionary.

		Args:
			params (Dict):
				Google Static Maps query parameters.

		Returns:
			str | None:
				Fully-qualified Google Static Maps URL.

	"""
	try:
		throw_if( 'params', params )
		params_value = dict( params or { } )
		params_value[ 'key' ] = self.api_key
		self.params = params_value
		return f'{self.base_url}?{urlencode( self.params, doseq=True )}'
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = "build_url( self, params: Dict ) -> str | None"
		Logger( ).write( exception )
		raise exception

pin

pin(
    lat: float,
    lng: float,
    zoom: int = 12,
    size: str = "400x300",
    scale: int = 1,
) -> str | None
Purpose

Build a static map URL centered on a coordinate with a single marker.

Parameters:

Name Type Description Default
lat float

Latitude for the pin.

required
lng float

Longitude for the pin.

required
zoom int

Zoom level from 1 through 20.

12
size str

Image dimensions in WxH format.

'400x300'
scale int

Google Static Maps image resolution multiplier, 1 or 2.

1

Returns:

Type Description
str | None

str | None: Fully-qualified URL string suitable for embedding.

Source code in mapping.py
def pin( self, lat: float, lng: float, zoom: int = 12, size: str = '400x300',
	scale: int = 1 ) -> str | None:
	"""

		Purpose:
			Build a static map URL centered on a coordinate with a single marker.

		Args:
			lat (float):
				Latitude for the pin.

			lng (float):
				Longitude for the pin.

			zoom (int):
				Zoom level from 1 through 20.

			size (str):
				Image dimensions in WxH format.

			scale (int):
				Google Static Maps image resolution multiplier, 1 or 2.

		Returns:
			str | None:
				Fully-qualified URL string suitable for embedding.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		latitude, longitude = self.validate_coordinate( lat, lng )
		zoom_value = max( 1, min( int( zoom or 12 ), 20 ) )
		if type( scale ) is not int or scale not in (1, 2):
			raise ValueError( 'scale must be 1 or 2.' )
		size_value = size or '400x300'
		marker_value = f'{latitude},{longitude}'
		self.latitude = latitude
		self.longitude = longitude
		self.zoom = zoom_value
		self.size = size_value
		self.scale = scale
		self.markers = marker_value
		self.params = { 'center': f'{self.latitude},{self.longitude}', 'zoom': str( self.zoom ),
			'size': self.size, 'scale': self.scale, 'markers': self.markers }
		return self.build_url( self.params )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = ("pin( self, lat: float, lng: float, zoom: int=12, "
		                    "size: str='400x300', scale: int=1 ) -> str | None")
		Logger( ).write( exception )
		raise exception

pins

pins(
    points: list,
    zoom: int = 0,
    size: int = "600x400",
    maptype: int = "roadmap",
    color: int = "red",
) -> str | None
Purpose

Build a static map URL with multiple markers. If zoom is zero, Google is allowed to fit the visible area to the supplied points.

Parameters:

Name Type Description Default
points list

List of coordinate tuples, coordinate lists, or dictionaries containing lat/lng fields.

required
zoom int

Zoom level. Use zero to omit explicit zoom.

0
size str

Image dimensions in WxH format.

'600x400'
maptype str

Map type: roadmap, satellite, terrain, or hybrid.

'roadmap'
color str

Marker color.

'red'

Returns:

Type Description
str | None

str | None: Fully-qualified URL string suitable for embedding.

Source code in mapping.py
def pins( self, points: list, zoom: int = 0, size: int = '600x400', maptype: int = 'roadmap',
	color: int = 'red' ) -> str | None:
	"""

		Purpose:
			Build a static map URL with multiple markers. If zoom is zero,
			Google is allowed to fit the visible area to the supplied points.

		Args:
			points (list):
				List of coordinate tuples, coordinate lists, or dictionaries
				containing lat/lng fields.

			zoom (int):
				Zoom level. Use zero to omit explicit zoom.

			size (str):
				Image dimensions in WxH format.

			maptype (str):
				Map type: roadmap, satellite, terrain, or hybrid.

			color (str):
				Marker color.

		Returns:
			str | None:
				Fully-qualified URL string suitable for embedding.

	"""
	try:
		throw_if( 'points', points )
		coordinates = self.normalize_points( points )
		zoom_value = int( zoom or 0 )
		size_value = size or '600x400'
		maptype_value = str( maptype or 'roadmap' ).strip( ).lower( )
		color_value = color or 'red'
		if maptype_value not in [ 'roadmap', 'satellite', 'terrain', 'hybrid' ]:
			raise ValueError( 'maptype must be roadmap, satellite, terrain, or hybrid.' )
		self.points = coordinates
		self.zoom = zoom_value
		self.size = size_value
		self.maptype = maptype_value
		self.color = color_value
		marker_values = [ ]
		for lat_value, lng_value in self.points:
			marker_values.append( f'color:{self.color}|{lat_value},{lng_value}' )
		self.params = { 'size': self.size, 'maptype': self.maptype, 'markers': marker_values }
		if self.zoom > 0:
			center_lat = sum( p[ 0 ] for p in self.points ) / len( self.points )
			center_lng = sum( p[ 1 ] for p in self.points ) / len( self.points )
			self.params[ 'center' ] = f'{center_lat},{center_lng}'
			self.params[ 'zoom' ] = str( max( 1, min( self.zoom, 20 ) ) )
		else:
			self.params[ 'visible' ] = [ f'{lat},{lng}' for lat, lng in self.points ]
		return self.build_url( self.params )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMapUrl'
		exception.method = (
			"pins( self, points: list, zoom: int=0, size: int='600x400', maptype: int='roadmap', "
			"color: int='red' ) -> str | None:")
		Logger( ).write( exception )
		raise exception

path

path(
    points: list,
    size: int = "600x400",
    maptype: int = "roadmap",
    color: int = "0x0000ff",
    weight: int = 5,
) -> str | None
Purpose

Build a static map URL showing a path through two or more points.

Parameters:

Name Type Description Default
points list

List of coordinate tuples, coordinate lists, or dictionaries containing lat/lng fields.

required
size str

Image dimensions in WxH format.

'600x400'
maptype str

Map type: roadmap, satellite, terrain, or hybrid.

'roadmap'
color str

Path color.

'0x0000ff'
weight int

Path stroke weight.

5

Returns:

Type Description
str | None

str | None: Fully-qualified URL string suitable for embedding.

Source code in mapping.py
def path( self, points: list, size: int = '600x400', maptype: int = 'roadmap',
	color: int = '0x0000ff', weight: int = 5 ) -> str | None:
	"""

		Purpose:
			Build a static map URL showing a path through two or more points.

		Args:
			points (list):
				List of coordinate tuples, coordinate lists, or dictionaries
				containing lat/lng fields.

			size (str):
				Image dimensions in WxH format.

			maptype (str):
				Map type: roadmap, satellite, terrain, or hybrid.

			color (str):
				Path color.

			weight (int):
				Path stroke weight.

		Returns:
			str | None:
				Fully-qualified URL string suitable for embedding.

	"""
	try:
		throw_if( 'points', points )
		coordinates = self.normalize_points( points )
		size_value = size or '600x400'
		maptype_value = str( maptype or 'roadmap' ).strip( ).lower( )
		color_value = color or '0x0000ff'
		weight_value = max( 1, int( weight or 5 ) )
		if len( coordinates ) < 2:
			raise ValueError( 'At least two coordinates are required for a path.' )
		if maptype_value not in [ 'roadmap', 'satellite', 'terrain', 'hybrid' ]:
			raise ValueError( 'maptype must be roadmap, satellite, terrain, or hybrid.' )
		self.points = coordinates
		self.size = size_value
		self.maptype = maptype_value
		self.color = color_value
		self.weight = weight_value
		path_points = [ f'{lat},{lng}' for lat, lng in self.points ]
		path_parts = [ f'color:{self.color}', f'weight:{self.weight}' ] + path_points
		path_value = '|'.join( path_parts )
		self.params = { 'size': self.size, 'maptype': self.maptype, 'path': path_value,
			'markers': [ f'color:green|{self.points[ 0 ][ 0 ]},{self.points[ 0 ][ 1 ]}',
				f'color:red|{self.points[ -1 ][ 0 ]},{self.points[ -1 ][ 1 ]}' ],
			'visible': path_points }
		return self.build_url( self.params )
	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = "path( self, **args ) -> str | None"
		Logger( ).write( exception )
		raise exception

bbox

bbox(
    west: float,
    south: float,
    east: float,
    north: float,
    size: int = "600x400",
    maptype: int = "roadmap",
) -> str | None
Purpose

Build a static map URL showing a rectangular bounding box.

Parameters:

Name Type Description Default
west float

Western longitude.

required
south float

Southern latitude.

required
east float

Eastern longitude.

required
north float

Northern latitude.

required
size str

Image dimensions in WxH format.

'600x400'
maptype str

Map type: roadmap, satellite, terrain, or hybrid.

'roadmap'

Returns:

Type Description
str | None

str | None: Fully-qualified URL string suitable for embedding.

Source code in mapping.py
def bbox( self, west: float, south: float, east: float, north: float, size: int = '600x400',
	maptype: int = 'roadmap' ) -> str | None:
	"""

		Purpose:
			Build a static map URL showing a rectangular bounding box.

		Args:
			west (float):
				Western longitude.

			south (float):
				Southern latitude.

			east (float):
				Eastern longitude.

			north (float):
				Northern latitude.

			size (str):
				Image dimensions in WxH format.

			maptype (str):
				Map type: roadmap, satellite, terrain, or hybrid.

		Returns:
			str | None:
				Fully-qualified URL string suitable for embedding.

	"""
	try:
		throw_if( 'west', west )
		throw_if( 'south', south )
		throw_if( 'east', east )
		throw_if( 'north', north )
		west_value = float( west )
		south_value = float( south )
		east_value = float( east )
		north_value = float( north )
		size_value = size or '600x400'
		maptype_value = maptype or 'roadmap'
		southwest = self.validate_coordinate( south_value, west_value )
		northwest = self.validate_coordinate( north_value, west_value )
		northeast = self.validate_coordinate( north_value, east_value )
		southeast = self.validate_coordinate( south_value, east_value )
		self.west = west_value
		self.south = south_value
		self.east = east_value
		self.north = north_value
		self.size = size_value
		self.maptype = maptype_value
		self.points = [ southwest, northwest, northeast, southeast, southwest ]
		return self.path( points=self.points, size=self.size, maptype=self.maptype,
			color='0xff0000', weight=3 )

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'StaticMap'
		exception.method = "bbox( self, **args ) -> str | None"
		Logger( ).write( exception )
		raise exception