Distance Matrix
distances
¶
Assembly: Mappy
Filename: distances.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
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¶
DistanceMatrix
¶
DistanceMatrix(maps: Maps)
Provide route, matrix, comparison, and dataframe helpers.
Purpose
Wraps the Google Distance Matrix API through the shared Maps gateway and
normalizes results into row-friendly dictionaries. The class supports single
route summaries, many-origin/many-destination matrices, mode comparisons,
metric conversions, and pandas DataFrame output for Streamlit display,
spreadsheet enrichment, and downstream analytics.
Attributes:
| Name | Type | Description |
|---|---|---|
_maps |
Maps
|
Shared Google Maps gateway used for Distance Matrix requests. |
modes |
List[str]
|
Supported Google Distance Matrix travel modes. |
data |
Dict[str, Any] | None
|
Raw Distance Matrix response payload from the latest request. |
rows |
List[Dict[str, Any]] | None
|
Flattened route rows from the latest matrix request. |
Initialize the Distance Matrix service wrapper.
Purpose
Stores the shared Google Maps gateway, supported travel modes, and runtime state used by matrix, summary, comparison, conversion, and dataframe helper methods. The constructor performs local assignment only and prepares the instance for later API-backed route operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maps
|
Maps
|
Google Maps gateway used for Distance Matrix API requests. |
required |
Source code in distances.py
Methods:¶
normalize_mode
¶
Validate and normalize a travel mode.
Purpose
Converts a requested travel mode to lowercase and verifies it is one of the Google Distance Matrix modes supported by Mappy. The normalized value is used in gateway parameters and route output rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
Travel mode such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Normalized travel mode. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or normalization fails. |
Source code in distances.py
normalize_inputs
¶
normalize_inputs(
values: (
List[AddressOrCoord]
| Tuple[AddressOrCoord, ...]
| AddressOrCoord
),
) -> List[AddressOrCoord]
Normalize one or many origins or destinations into a list.
Purpose
Accepts a single address, a single coordinate tuple, a list of addresses or coordinates, or a tuple of values and returns a list shape suitable for Distance Matrix query construction. Single coordinate tuples are preserved as one coordinate instead of being expanded into two independent values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
List[AddressOrCoord] | Tuple[AddressOrCoord, ...] | AddressOrCoord
|
Single origin/destination value or a collection of values. |
required |
Returns:
| Type | Description |
|---|---|
List[AddressOrCoord]
|
List[AddressOrCoord]: Normalized input list. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or normalization fails. |
Source code in distances.py
convert_distance
¶
Convert meters into kilometers and miles.
Purpose
Normalizes Google Distance Matrix meter values into kilometer and mile
fields used by summaries, matrix rows, dataframe output, and Streamlit
display. Missing distance values are preserved as None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
meters
|
int | float | None
|
Distance in meters. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, float | None]
|
Dict[str, float | None]: Dictionary containing |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when conversion fails. |
Source code in distances.py
convert_duration
¶
Convert seconds into minutes and hours.
Purpose
Normalizes Google Distance Matrix duration values into minute and hour
fields used by summaries, matrix rows, dataframe output, and Streamlit
display. Missing duration values are preserved as None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
int | float | None
|
Duration in seconds. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, float | None]
|
Dict[str, float | None]: Dictionary containing |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when conversion fails. |
Source code in distances.py
flatten_element
¶
flatten_element(
origin: str,
destination: str,
mode: str,
element: Dict[str, Any],
) -> Dict[str, Any]
Flatten one Distance Matrix element into a route row.
Purpose
Converts one Google Distance Matrix element into a dictionary containing origin, destination, mode, status, text fields, raw meter/second values, converted distance values, converted duration values, and traffic-aware duration values when available. The row shape is reused by summary, comparison, dataframe, and Streamlit display workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
str
|
Resolved origin label from the API or fallback input value. |
required |
destination
|
str
|
Resolved destination label from the API or fallback input value. |
required |
mode
|
str
|
Travel mode used for the request. |
required |
element
|
Dict[str, Any]
|
One Distance Matrix element dictionary. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Flattened route row. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation or row flattening fails. |
Source code in distances.py
matrix
¶
matrix(
origins: (
List[AddressOrCoord]
| Tuple[AddressOrCoord, ...]
| AddressOrCoord
),
destinations: (
List[AddressOrCoord]
| Tuple[AddressOrCoord, ...]
| AddressOrCoord
),
mode: str = "driving",
departure_time: str = "",
) -> List[Dict[str, Any]]
Execute a Distance Matrix request.
Purpose
Builds a Distance Matrix request for one or more origins and destinations, normalizes the selected travel mode, optionally applies a departure time, calls the shared Google Maps gateway, and flattens each returned element into route rows. The latest raw payload and flattened rows are stored on the instance for summaries, comparisons, dataframe conversion, and UI inspection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origins
|
List[AddressOrCoord] | Tuple[AddressOrCoord, ...] | AddressOrCoord
|
Single origin or collection of origins. |
required |
destinations
|
List[AddressOrCoord] | Tuple[AddressOrCoord, ...] | AddressOrCoord
|
Single destination or collection of destinations. |
required |
mode
|
str
|
Travel mode such as |
'driving'
|
departure_time
|
str
|
Optional departure time. Use |
''
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: Flattened route rows. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation, gateway execution, response handling, or row flattening fails. |
Source code in distances.py
summary
¶
Return a compact route summary.
Purpose
Executes a one-origin, one-destination matrix request and returns the first flattened route as a compact summary containing distance, duration, traffic-aware duration, origin, destination, mode, and status fields. When no rows are returned, the method preserves a predictable no-results shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
AddressOrCoord
|
Origin address string or |
required |
destination
|
AddressOrCoord
|
Destination address string or |
required |
mode
|
str
|
Travel mode such as |
'driving'
|
Returns:
| Name | Type | Description |
|---|---|---|
Dict |
Dict
|
Compact distance and duration summary. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when matrix execution or summary construction fails. |
Source code in distances.py
compare_modes
¶
compare_modes(
origin: AddressOrCoord,
destination: AddressOrCoord,
modes: List[str] | None = None,
departure_time: str = "",
) -> List[Dict[str, Any]]
Compare route results across travel modes.
Purpose
Executes a single-route matrix request for each selected travel mode and returns the first flattened route row for each successful mode. Driving requests can preserve the supplied departure time for traffic-aware results, while non-driving modes omit it to avoid unsupported combinations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
AddressOrCoord
|
Origin address string or coordinate tuple. |
required |
destination
|
AddressOrCoord
|
Destination address string or coordinate tuple. |
required |
modes
|
List[str] | None
|
Optional travel modes to compare. Defaults to all supported modes. |
None
|
departure_time
|
str
|
Optional departure time. Use |
''
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List[Dict[str, Any]]: One flattened route row per successful travel mode. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when validation, matrix execution, or comparison construction fails. |
Source code in distances.py
to_dataframe
¶
Convert route rows into a pandas DataFrame.
Purpose
Transforms caller-supplied rows or the latest matrix rows into a DataFrame for Streamlit display, CSV/Excel export, diagnostics, or downstream analytics. Missing or empty rows return an empty DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
List[Dict[str, Any]] | None
|
Optional route rows. Defaults to the most recent matrix rows. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: Route results as a DataFrame. |
Raises:
| Type | Description |
|---|---|
Error
|
Raised after logging when dataframe conversion fails. |
Source code in distances.py
Functions:¶
throw_if
¶
Validate that a required distance-matrix value is present.
Purpose
Provides a lightweight guard for required Distance Matrix inputs before mode normalization, origin/destination formatting, gateway request construction, and row flattening. The function rejects missing objects and blank strings so route workflows fail before issuing ambiguous 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 distances.py
fmt
¶
Normalize an address or coordinate for the Distance Matrix API.
Purpose
Converts a coordinate tuple into the lat,lng string expected by Google
Distance Matrix requests while preserving free-form address strings. The
helper is used when constructing origin and destination query strings and
when fallback labels are needed for flattened route rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
o
|
AddressOrCoord
|
Address string or |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
API-ready origin or destination text. |