Geocoding
geocode
¶
Assembly: Mappy
Filename: geocode.py
Author: Terry D. Eppler
Created: 05-31-2022
Last Modified By: Terry D. Eppler
Last Modified On: 05-01-2025
Mappy is a python framework encapsulating the Google Maps functionality.
Copyright © 2022 Terry Eppler
Purpose:
High-level Geocoding service that resolves addresses or city/state/country
triples into canonical address stores and coordinates.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov
Classes¶
Geocoder
¶
Provide forward, reverse, structured, and batch geocoding.
Purpose
Coordinates Google Geocoding API requests through the shared Maps gateway
and optional cache backend. The class resolves free-form addresses,
latitude/longitude pairs, and city/state/country triples into a consistent
flattened output shape used by Streamlit workflows, Excel/CSV enrichment,
local data-management updates, and downstream location intelligence tasks.
Attributes:
| Name | Type | Description |
|---|---|---|
maps |
Optional[Maps]
|
Public reference to the Google Maps gateway. |
cache |
Optional[BaseCache]
|
Optional public cache backend reference. |
prefix |
Optional[str]
|
Cache namespace prefix used during key construction. |
data |
Optional[Dict]
|
Raw response payload returned by the Google Maps gateway. |
output |
Optional[Dict]
|
Last flattened geocoding result. |
parts |
Optional[Tuple]
|
Structured query or cache-key parts from the latest request. |
city |
Optional[str]
|
City value from the latest structured lookup. |
address |
Optional[str]
|
Free-form address value from the latest lookup. |
state |
Optional[str]
|
State, province, territory, or region from the latest lookup. |
country |
Optional[str]
|
Country or country bias from the latest lookup. |
comps |
Optional[Dict[str, str]]
|
Optional component parameters sent to the Geocoding API. |
key |
Optional[str]
|
Cache key for the latest lookup. |
query |
Optional[str]
|
Query text built for the latest structured lookup. |
latitude |
Optional[float]
|
Latitude from the latest reverse-geocode lookup. |
longitude |
Optional[float]
|
Longitude from the latest reverse-geocode lookup. |
Initialize the geocoding service wrapper.
Purpose
Stores the shared Google Maps gateway, optional cache backend, and runtime state used by forward, reverse, structured, and batch geocoding methods. The constructor performs local assignment only and prepares the instance for later API-backed lookup operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maps
|
Maps
|
Google Maps gateway used for Geocoding API requests. |
required |
cache
|
Optional[BaseCache]
|
Optional cache backend used to store and retrieve lookup results. |
None
|
Source code in geocode.py
Methods:¶
key_for
¶
Build a stable cache key for a geocoding operation.
Purpose
Combines an operation prefix and one or more identifying values into the cache-key format used by forward and reverse geocoding. The method stores the latest prefix and parts on the instance so cache behavior can be inspected during debugging and Streamlit workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Cache namespace or operation prefix. |
required |
*parts
|
str
|
Values that uniquely identify the request. |
()
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: Normalized cache key. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or key construction fails. |
Source code in geocode.py
validate_coordinates
¶
Validate and normalize a latitude/longitude pair.
Purpose
Converts coordinate inputs to floats and enforces valid geographic ranges before reverse-geocoding requests are sent to the Google Geocoding API. The method prevents invalid coordinates from reaching cache-key generation or gateway request construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latitude
|
float
|
Latitude in decimal degrees. |
required |
longitude
|
float
|
Longitude in decimal degrees. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
Tuple[float, float]: Validated latitude and longitude values. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or conversion fails. |
Source code in geocode.py
freeform
¶
Geocode a free-form address string.
Purpose
Resolves a human-readable address through the Google Geocoding API with an optional country bias. The method checks the cache before calling the gateway, stores raw and flattened response state on the instance, writes successful lookups back to the cache, and returns Mappy's canonical location output shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
Human-entered address, place, or location text. |
required |
country
|
str
|
Optional ISO-3166 alpha-2 country code used as a result bias. |
'US'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any] | None
|
Dict[str, Any] | None: Flattened geocode result. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation, lookup, gateway handling, or result processing fails. |
Source code in geocode.py
reverse
¶
Reverse geocode a latitude/longitude coordinate pair.
Purpose
Resolves geographic coordinates into a canonical address using the Google Geocoding API. The method validates coordinates, checks the cache, stores raw and flattened response state on the instance, writes successful lookups to the cache, and returns the same row-friendly shape used by forward geocoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latitude
|
float
|
Latitude in decimal degrees. |
required |
longitude
|
float
|
Longitude in decimal degrees. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any] | None
|
Dict[str, Any] | None: Flattened reverse-geocode result. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation, lookup, gateway handling, or result processing fails. |
Source code in geocode.py
city_state_country
¶
Geocode a structured city, state, and country query.
Purpose
Builds a free-form geocoding query from structured locality fields and
delegates to freeform so caching, gateway execution, response flattening,
and error handling remain consistent with ordinary address lookups. The
method stores the structured parts and final query on the instance for later
inspection by enrichment or UI workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
city
|
str
|
City or locality value. |
required |
state
|
str
|
State, province, territory, or region value. |
required |
country
|
str
|
Country name or short country code. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any] | None
|
Dict[str, Any] | None: Flattened geocode result. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or delegated geocoding fails. |
Source code in geocode.py
batch_freeform
¶
Geocode a list of free-form addresses.
Purpose
Processes multiple address strings while preserving row-level status for
successful lookups, skipped empty rows, and failed lookups. The method uses
freeform for each populated address so cache behavior, gateway calls, and
flattened output remain consistent with single-record geocoding workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
addresses
|
List[str]
|
Address strings to geocode. |
required |
country
|
str
|
ISO-3166 alpha-2 country code used as the default country bias. |
'US'
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: Flattened row-level geocode results with
|
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when batch-level validation or processing fails. |
Source code in geocode.py
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
Functions:¶
throw_if
¶
Validate that a required geocoding value is present.
Purpose
Provides a lightweight guard for required Geocoder inputs before cache-key construction, coordinate validation, gateway requests, and batch processing. The function rejects missing objects and blank strings so geocoding workflows fail with clear validation messages before issuing external API calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the argument being validated. |
required |
value
|
object
|
Runtime value to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when |
Source code in geocode.py
flatten_geocode
¶
Flatten a Google Geocoding result into Mappy's canonical row shape.
Purpose
Extracts the formatted address, coordinates, place identifier, result types, country values, administrative areas, locality, and postal code from one Google Geocoding API result. The returned dictionary is used by single-record geocoding, reverse geocoding, batch geocoding, spreadsheet enrichment, and Streamlit result previews.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Dict[str, Any]
|
One result dictionary from the Google Geocoding API |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Flattened geocode output suitable for rows, cache payloads, and UI display. |