API Reference¶
gpx.gpx Module¶
GPX model for GPX data.
This module provides the GPX model representing the root GPX document, following the GPX 1.1 specification.
- gpx.gpx.GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1'¶
GPX 1.1 namespace
- gpx.gpx.XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'¶
XML Schema instance namespace
- class gpx.gpx.GPX(creator='https://github.com/sgraaf/gpx', *, metadata=None, wpt=<factory>, rte=<factory>, trk=<factory>, extensions=None, nsmap=None)¶
Bases:
GeoGPXModelThe root GPX document.
GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements to the extensions section of the GPX document.
Note: The GPX version is always “1.1” per the specification and is automatically set during XML serialization.
- Parameters:
creator (str) – The name or URL of the software that created the GPX document. Defaults to “https://github.com/sgraaf/gpx”.
metadata (Metadata | None) – Metadata about the file. Defaults to None.
wpt (list[Waypoint]) – List of waypoints. Defaults to empty list.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
nsmap (dict[str, str] | None) – Namespace prefix mappings from the original XML. Defaults to None. This is used internally to preserve namespace prefixes during round-trip parsing. Users typically don’t need to set this.
- property __geo_interface__: dict[str, Any]¶
Return the GPX as a GeoJSON-like FeatureCollection.
- Returns:
A dictionary representing a GeoJSON FeatureCollection containing all waypoints, routes, and tracks.
- to_xml(tag=None, nsmap=None)¶
Convert the GPX to an XML element.
- Parameters:
tag (str | None) – The XML tag name. Defaults to “gpx”.
nsmap (dict[str | None, str] | None) – Optional namespace mapping. Defaults to GPX 1.1 namespace with XML Schema instance namespace. If the GPX instance has stored namespace mappings (from parsing), those will be used to preserve original namespace prefixes.
- Returns:
The XML element.
- Return type:
- to_string(*, pretty_print=True)¶
Serialize the GPX instance to a string.
- Parameters:
pretty_print (bool) – Whether to format the output with indentation. Defaults to True.
- Returns:
The GPX data as a string.
- Return type:
Example
>>> from gpx import GPX >>> gpx = GPX(creator="MyApp") >>> xml_string = gpx.to_string() >>> print(xml_string[:50]) <?xml version='1.0' encoding='UTF-8'?> <gpx ve
- write_gpx(file_path, *, pretty_print=True)¶
Write the GPX to a file.
- Parameters:
Example
>>> from gpx import GPX >>> gpx = GPX(creator="MyApp") >>> gpx.write_gpx("output.gpx")
- write_geojson(file_path, *, indent=2)¶
Write the GPX to a GeoJSON file.
- Parameters:
Example
>>> from gpx import GPX >>> gpx = GPX() >>> gpx.write_geojson("output.geojson")
- write_kml(file_path, *, pretty_print=True)¶
Write the GPX to a KML file.
- Parameters:
Example
>>> from gpx import GPX >>> gpx = GPX() >>> gpx.write_kml("output.kml")
- to_wkt()¶
Convert the GPX to a WKT (Well-Known Text) string.
Returns a GeometryCollection containing all waypoints, routes, and tracks.
- Returns:
A WKT string representation of the GPX data.
- Return type:
Example
>>> from gpx import GPX, Waypoint >>> from decimal import Decimal >>> gpx = GPX(wpt=[Waypoint(Decimal("52.0"), Decimal("4.0"))]) >>> print(gpx.to_wkt()) GEOMETRYCOLLECTION (POINT (4.0 52.0))
- to_wkb(*, byte_order='little')¶
Convert the GPX to WKB (Well-Known Binary).
Returns a GeometryCollection containing all waypoints, routes, and tracks.
- Parameters:
byte_order (str) – Byte order for the binary data. Either “little” (NDR) or “big” (XDR). Defaults to “little”.
- Returns:
WKB bytes representation of the GPX data.
- Return type:
Example
>>> from gpx import GPX, Waypoint >>> from decimal import Decimal >>> gpx = GPX(wpt=[Waypoint(Decimal("52.0"), Decimal("4.0"))]) >>> wkb = gpx.to_wkb()
gpx.metadata Module¶
Metadata model for GPX data.
This module provides the Metadata model containing information about the GPX file, author, and copyright restrictions, following the GPX 1.1 specification.
- class gpx.metadata.Metadata(*, name=None, desc=None, author=None, copyright=None, link=<factory>, time=None, keywords=None, bounds=None, extensions=None)¶
Bases:
GPXModelInformation about the GPX file, author, and copyright restrictions.
Providing rich, meaningful information about your GPX files allows others to search for and use your GPS data.
- Parameters:
name (str | None) – The name of the GPX file. Defaults to None.
desc (str | None) – A description of the contents of the GPX file. Defaults to None.
author (Person | None) – The person or organization who created the GPX file. Defaults to None.
copyright (Copyright | None) – Copyright and license information governing use of the file. Defaults to None.
link (list[Link]) – URLs associated with the location described in the file. Defaults to empty list.
time (datetime | None) – The creation date of the file. Defaults to None.
keywords (str | None) – Keywords associated with the file. Search engines or databases can use this information to classify the data. Defaults to None.
bounds (Bounds | None) – Minimum and maximum coordinates which describe the extent of the coordinates in the file. Defaults to None.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
gpx.waypoint Module¶
Waypoint model for GPX data.
This module provides the Waypoint model representing a waypoint, point of interest, or named feature on a map, following the GPX 1.1 specification.
- class gpx.waypoint.Waypoint(lat, lon, *, ele=None, time=None, magvar=None, geoidheight=None, name=None, cmt=None, desc=None, src=None, link=<factory>, sym=None, type=None, fix=None, sat=None, hdop=None, vdop=None, pdop=None, ageofdgpsdata=None, dgpsid=None, extensions=None)¶
Bases:
GeoGPXModelA waypoint, point of interest, or named feature on a map.
- Parameters:
lat (Latitude) – Latitude of the point in decimal degrees, WGS84 datum.
lon (Longitude) – Longitude of the point in decimal degrees, WGS84 datum.
ele (Decimal | None) – Elevation (in meters) of the point. Defaults to None.
time (datetime | None) – Creation/modification timestamp for element (UTC). Defaults to None.
magvar (Degrees | None) – Magnetic variation (in degrees) at the point. Defaults to None.
geoidheight (Decimal | None) – Height (in meters) of geoid (mean sea level) above WGS84 earth ellipsoid. Defaults to None.
name (str | None) – GPS name of the waypoint. Defaults to None.
cmt (str | None) – GPS waypoint comment. Defaults to None.
desc (str | None) – Text description of the element. Defaults to None.
src (str | None) – Source of data. Defaults to None.
link (list[Link]) – Links to additional information about the waypoint. Defaults to empty list.
sym (str | None) – Text of GPS symbol name. Defaults to None.
type (str | None) – Type (classification) of the waypoint. Defaults to None.
fix (Fix | None) – Type of GPX fix. Defaults to None.
sat (int | None) – Number of satellites used to calculate the GPX fix. Defaults to None.
hdop (Decimal | None) – Horizontal dilution of precision. Defaults to None.
vdop (Decimal | None) – Vertical dilution of precision. Defaults to None.
pdop (Decimal | None) – Position dilution of precision. Defaults to None.
ageofdgpsdata (Decimal | None) – Number of seconds since last DGPS update. Defaults to None.
dgpsid (DGPSStation | None) – ID of DGPS station used in differential correction. Defaults to None.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
- property __geo_interface__: dict[str, Any]¶
Return the waypoint as a GeoJSON-like Point geometry or Feature.
Returns a Feature if any optional fields (excluding ele) are set, otherwise returns a pure Point geometry.
- Returns:
A dictionary representing either a GeoJSON Point geometry or Feature.
- distance_to(other, radius=6378137)¶
Return the distance to another waypoint using the haversine formula.
Uses a simple spherical earth model (haversine formula).
- duration_to(other)¶
Return the duration to another waypoint.
- speed_to(other)¶
Return the speed to another waypoint.
- gain_to(other)¶
Return the elevation gain to another waypoint.
gpx.route Module¶
Route model for GPX data.
This module provides the Route model representing an ordered list of waypoints representing a series of turn points leading to a destination, following the GPX 1.1 specification.
- class gpx.route.Route(*, name=None, cmt=None, desc=None, src=None, link=<factory>, number=None, type=None, extensions=None, rtept=<factory>)¶
Bases:
PointsMixin,GeoGPXModelAn ordered list of waypoints representing a series of turn points.
A route represents waypoints leading to a destination.
- Parameters:
name (str | None) – GPS name of route. Defaults to None.
cmt (str | None) – GPS comment for route. Defaults to None.
desc (str | None) – Text description of route for user. Defaults to None.
src (str | None) – Source of data. Defaults to None.
link (list[Link]) – Links to external information about the route. Defaults to empty list.
number (int | None) – GPS route number. Defaults to None.
type (str | None) – Type (classification) of route. Defaults to None.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
rtept (list[Waypoint]) – List of route points. Defaults to empty list.
gpx.track Module¶
Track model for GPX data.
This module provides the Track model representing an ordered list of points describing a path, following the GPX 1.1 specification.
- class gpx.track.Track(*, name=None, cmt=None, desc=None, src=None, link=<factory>, number=None, type=None, extensions=None, trkseg=<factory>)¶
Bases:
PointsMixin,GeoGPXModelAn ordered list of points describing a path.
A track represents a GPS track consisting of track segments.
- Parameters:
name (str | None) – GPS name of track. Defaults to None.
cmt (str | None) – GPS comment for track. Defaults to None.
desc (str | None) – User description of track. Defaults to None.
src (str | None) – Source of data. Defaults to None.
link (list[Link]) – Links to external information about track. Defaults to empty list.
number (int | None) – GPS track number. Defaults to None.
type (str | None) – Type (classification) of track. Defaults to None.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
trkseg (list[TrackSegment]) – List of track segments. Defaults to empty list.
- property __geo_interface__: dict[str, Any]¶
Return the track as a GeoJSON-like MultiLineString geometry or Feature.
Returns a Feature if any optional fields are set, otherwise returns a pure MultiLineString geometry.
- Returns:
A dictionary representing either a GeoJSON MultiLineString geometry or Feature.
- property moving_duration: timedelta¶
The moving duration of the track.
The moving duration is the total duration with a speed greater than 0.5 km/h.
gpx.extensions Module¶
GPX Extensions container for arbitrary namespace extensions.
This module provides the Extensions class that stores raw XML elements from any namespace, enabling lossless round-trip parsing while providing convenient accessor methods for reading and writing extension data.
- class gpx.extensions.Extensions(elements=<factory>)¶
Bases:
objectContainer for GPX extension elements from any namespace.
Stores raw XML elements from extension namespaces (non-GPX namespaces), enabling lossless round-trip parsing. Provides convenient accessor methods for reading and writing extension data without requiring knowledge of specific extension schemas.
This class is schema-agnostic and works with ANY GPX extension, including but not limited to Garmin, Strava, Cluetrust, and custom extensions.
Example
Reading extension data:
from gpx import read_gpx gpx = read_gpx("activity.gpx") # Define namespace for the extension you're looking for GARMIN_TPX = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2" for track in gpx.tracks: for segment in track.segments: for point in segment.points: if point.extensions: hr = point.extensions.get_text("hr", namespace=GARMIN_TPX) if hr: print(f"Heart rate: {hr} bpm")
Creating extension data:
import xml.etree.ElementTree as ET from gpx import Waypoint, Extensions # Register namespace prefix GARMIN_TPX = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2" ET.register_namespace("gpxtpx", GARMIN_TPX) # Create extension element tpx = ET.Element(f"{{{GARMIN_TPX}}}TrackPointExtension") hr = ET.SubElement(tpx, f"{{{GARMIN_TPX}}}hr") hr.text = "142" # Attach to waypoint point = Waypoint(lat=..., lon=..., extensions=Extensions(elements=[tpx]))
- copy()¶
Create a deep copy of this Extensions instance.
- Returns:
A new Extensions instance with copies of all elements.
- Return type:
- find(path, namespaces=None)¶
Find a child element using XPath.
Searches through all top-level extension elements for a matching descendant.
- Parameters:
- Returns:
The first matching element, or None if not found.
- Return type:
Element | None
Example
>>> ns = {"gpxtpx": "http://www.garmin.com/xmlschemas/TrackPointExtension/v2"} >>> hr_elem = extensions.find("gpxtpx:TrackPointExtension/gpxtpx:hr", ns)
- findall(path, namespaces=None)¶
Find all matching child elements using XPath.
- get_text(tag, namespace=None, default=None)¶
Get text content of an extension element.
Searches through all extension elements and their descendants for an element with the specified tag name.
- Parameters:
- Returns:
The text content of the element, or the default value.
- Return type:
str | None
Example
>>> # Get heart rate from Garmin extension >>> GARMIN_TPX = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2" >>> hr = extensions.get_text("hr", namespace=GARMIN_TPX) >>> print(f"Heart rate: {hr} bpm")
>>> # Search any namespace >>> hr = extensions.get_text("hr")
- get_int(tag, namespace=None, default=None)¶
Get integer value of an extension element.
- Parameters:
- Returns:
The integer value, or the default value.
- Return type:
int | None
Example
>>> hr = extensions.get_int("hr", namespace=GARMIN_TPX) >>> print(f"Heart rate: {hr} bpm")
- get_float(tag, namespace=None, default=None)¶
Get float value of an extension element.
- Parameters:
- Returns:
The float value, or the default value.
- Return type:
float | None
Example
>>> temp = extensions.get_float("atemp", namespace=GARMIN_TPX) >>> print(f"Temperature: {temp}C")
- set_text(tag, value, namespace, parent_tag=None)¶
Set text content of an extension element, creating it if needed.
If the element exists, updates its text content. If it doesn’t exist, creates a new element with the specified namespace.
- Parameters:
tag (str) – The element tag name (local name).
value (str) – The text content to set.
namespace (str) – The namespace URI (required for creation).
parent_tag (str | None) – Optional parent element tag. If specified and the parent exists, the new element is added as a child of the parent. Otherwise, a new top-level element is created.
Example
>>> GARMIN_TPX = "http://www.garmin.com/xmlschemas/TrackPointExtension/v2" >>> extensions.set_text("hr", "145", namespace=GARMIN_TPX, ... parent_tag="TrackPointExtension")
- remove(tag, namespace=None)¶
Remove an extension element.
Removes the first matching element with the specified tag.
- clear()¶
Remove all extension elements.
- append(element)¶
Append an extension element.
- Parameters:
element (Element) – The XML element to append.
- extend(elements)¶
Extend with multiple extension elements.
- get_namespaces()¶
Get all namespaces used in extension elements.
Example
>>> namespaces = extensions.get_namespaces() >>> for ns in namespaces: ... print(f"Found extension namespace: {ns}")
- classmethod from_xml(element)¶
Parse extensions from an XML <extensions> element.
Creates deep copies of all child elements to ensure the parsed extensions are independent of the source XML tree.
- Parameters:
element (Element) – The <extensions> XML element.
- Returns:
An Extensions instance containing copies of all child elements.
- Return type:
- to_xml(tag=None, nsmap=None)¶
Convert to an XML <extensions> element.
gpx.track_segment Module¶
TrackSegment model for GPX data.
This module provides the TrackSegment model representing a list of track points which are logically connected in order, following the GPX 1.1 specification.
- class gpx.track_segment.TrackSegment(*, trkpt=<factory>, extensions=None)¶
Bases:
PointsMixin,GeoGPXModelA track segment holding a list of logically connected track points.
A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data.
- Parameters:
trkpt (list[Waypoint]) – List of track points. Defaults to empty list.
extensions (Extensions | None) – Extension elements from other XML namespaces. Defaults to None.
gpx.copyright Module¶
Copyright model for GPX data.
This module provides the Copyright model containing information about the copyright holder and any license governing use of the GPX data, following the GPX 1.1 specification.
gpx.link Module¶
Link model for GPX data.
This module provides the Link model representing a link to an external resource (Web page, digital photo, video clip, etc) with additional information, following the GPX 1.1 specification.
gpx.email Module¶
Email model for GPX data.
This module provides the Email model representing an email address broken into two parts (id and domain) to help prevent email harvesting, following the GPX 1.1 specification.
gpx.person Module¶
Person model for GPX data.
This module provides the Person model representing a person or organization, following the GPX 1.1 specification.
gpx.bounds Module¶
Bounds model for GPX data.
This module provides the Bounds model representing two lat/lon pairs defining the extent of an element, following the GPX 1.1 specification.
- class gpx.bounds.Bounds(minlat, minlon, maxlat, maxlon)¶
Bases:
GeoGPXModelTwo lat/lon pairs defining the extent of an element.
- Parameters:
- property __geo_interface__: dict[str, Any]¶
Return the Bounds as a GeoJSON-like Polygon.
The bounds are represented as a rectangular Polygon following the GeoJSON specification.
- Returns:
A dictionary with ‘type’ and ‘coordinates’ keys representing the bounds as a Polygon. Coordinates use [longitude, latitude] order as per GeoJSON convention.
gpx.types Module¶
This module provides simple type objects to contain various GPX data.
- class gpx.types.Latitude(value)¶
Bases:
DecimalA latitude class for the GPX data format.
The latitude of the point. Decimal degrees, WGS84 datum.
- Parameters:
- Raises:
ValueError – If the value is not a valid latitude (i.e. between [-90.0, 90.0]).
- class gpx.types.Longitude(value)¶
Bases:
DecimalA longitude class for the GPX data format.
The longitude of the point. Decimal degrees, WGS84 datum.
- Parameters:
- Raises:
ValueError – If the value is not a valid latitude (i.e. between [-180.0, 180.0]).
- class gpx.types.Degrees(value)¶
Bases:
DecimalA degrees class for the GPX data format.
Used for bearing, heading, course. Units are decimal degrees, true (not magnetic).
- Parameters:
- Raises:
ValueError – If the value is not a valid latitude (i.e. between [0.0, 360.0)).
- class gpx.types.Fix(value)¶
Bases:
strA fix class for the GPX data format.
Type of GPS fix. None means GPS had no fix. To signify “the fix info is unknown”, leave out fix entirely. pps = military signal used.
- Parameters:
value (str) – The fix value.
- Raises:
ValueError – If the value is not a valid fix (i.e. one of none, 2d, 3d, dgps, pps).
- class gpx.types.DGPSStation(value)¶
Bases:
intA DGPS station class for the GPX data format.
Represents a differential GPS station.
- Parameters:
- Raises:
ValueError – If the value is not a valid DGPS station (i.e. between [0, 1023]).
gpx.base Module¶
Base class for GPX dataclass models.
This module provides the base class that all GPX dataclass models inherit from, implementing common XML parsing and serialization logic.
- gpx.base.GPX_NAMESPACE = 'http://www.topografix.com/GPX/1/1'¶
GPX 1.1 namespace
- class gpx.base.GPXModel¶
Bases:
objectBase class for GPX dataclass models.
Provides common XML parsing and serialization methods. Subclasses must define the _tag class attribute to specify the default XML tag name.
- classmethod from_xml(element)¶
Parse the model from an XML element.
- Parameters:
element (Element) – The XML element to parse.
- Returns:
The parsed model instance.
- Raises:
ValueError – If required attributes are missing.
- Return type:
- to_xml(tag=None, nsmap=None)¶
Convert the model to an XML element.
- class gpx.base.GeoGPXModel¶
-
Base class for GPX dataclass models that carry geometric data.
Subclasses must implement
__geo_interface__to expose their geometry as a GeoJSON-compatible mapping. Inheriting from this class makes “this GPX model has geometry” expressible viaisinstance()and type hints.
gpx.mixins Module¶
This module provides mixin classes.
- class gpx.mixins.PointsMixin¶
Bases:
objectA mixin class to provide various statistics to an object’s points.
Implementing classes must provide
_points, returning a flat list of waypoints to aggregate over. The mixin intentionally does not define__iter__,__getitem__or__len__— those depend on the semantics of the host class (e.g.Trackiterates segments whileRoute/TrackSegmentiterate points) and belong on the host.- property __geo_interface__: dict[str, Any]¶
Return the route/track segment as a GeoJSON-like LineString geometry or Feature.
Returns a Feature if any optional fields are set, otherwise returns a pure LineString geometry.
- Returns:
A dictionary representing either a GeoJSON LineString geometry or Feature.
- property bounds: tuple[Latitude, Longitude, Latitude, Longitude]¶
The bounds of the route/track segment.
- property moving_duration: timedelta¶
The moving duration.
The moving duration is the total duration with a speed greater than 0.5 km/h.
gpx.convert Module¶
Conversion functions for converting data formats to GPX.
This module provides functions for converting from GeoJSON-like objects, WKB, and WKT data formats to GPX objects.
- gpx.convert.WKB_POINT = 1¶
WKB geometry type codes
- gpx.convert.WKB_Z_FLAG = 1000¶
Z dimension flag (add to base type for 3D)
- gpx.convert.EWKB_Z_FLAG = 2147483648¶
EWKB Z flag (high bit)
- gpx.convert.from_string(gpx_str)¶
Create a GPX instance from a string.
- Parameters:
gpx_str (str) – The string containing the GPX data.
- Returns:
The GPX instance with namespace prefixes preserved.
- Return type:
Example
>>> from gpx import from_string >>> gpx = from_string('''<?xml version="1.0"?> ... <gpx version="1.1" creator="MyApp"> ... <metadata><name>My Track</name></metadata> ... </gpx>''') >>> print(gpx.creator) MyApp
- gpx.convert.from_geo_interface(geo, *, creator=None)¶
Convert a GeoJSON-like object (with __geo_interface__ property) to GPX.
This function supports Python objects that implement the __geo_interface__ protocol (e.g., Shapely geometries) as well as raw GeoJSON dictionaries.
- Parameters:
geo (dict[str, Any] | SupportsGeoInterface) – A dictionary with GeoJSON structure or an object with __geo_interface__ property.
creator (str | None) – The creator string for the GPX. Defaults to None (uses default).
- Returns:
A GPX object.
- Raises:
ValueError – If the geometry type is not supported.
- Return type:
Example
>>> from shapely.geometry import Point >>> from gpx import from_geo_interface >>> point = Point(4.0, 52.0) >>> gpx = from_geo_interface(point)
- gpx.convert.from_wkb(wkb, *, creator=None)¶
Convert Well-Known Binary (WKB) to GPX.
Supports both standard WKB and EWKB (Extended WKB) with Z coordinates.
- Parameters:
- Returns:
A GPX object.
- Raises:
ValueError – If the WKB format is invalid or geometry type is unsupported.
- Return type:
Example
>>> from gpx import from_wkb >>> # WKB for POINT(4.0 52.0) >>> wkb = bytes.fromhex("0101000000000000000000104000000000004a4a40") >>> gpx = from_wkb(wkb)
- gpx.convert.from_wkt(wkt, *, creator=None)¶
Convert Well-Known Text (WKT) to GPX.
- Parameters:
- Returns:
A GPX object.
- Raises:
ValueError – If the WKT format is invalid or geometry type is unsupported.
- Return type:
Example
>>> from gpx import from_wkt >>> gpx = from_wkt("POINT (4.0 52.0)")
gpx.io Module¶
I/O functions for reading file formats into GPX.
This module provides functions for reading GPX, GeoJSON, and KML files from disk and returning GPX objects.
- gpx.io.KML_NAMESPACE = 'http://www.opengis.net/kml/2.2'¶
KML namespace
- gpx.io.read_gpx(file_path)¶
Read a GPX file and return a GPX object.
- Parameters:
- Returns:
A GPX object with namespace prefixes preserved.
- Return type:
Example
>>> from gpx import read_gpx >>> gpx = read_gpx("path/to/file.gpx")
- gpx.io.read_geojson(file_path, *, creator=None)¶
Read a GeoJSON file and return a GPX object.
- Parameters:
- Returns:
A GPX object.
- Return type:
Example
>>> from gpx import read_geojson >>> gpx = read_geojson("path/to/file.geojson")
- gpx.io.read_kml(file_path, *, creator=None)¶
Read a KML file and return a GPX object.
- Parameters:
- Returns:
A GPX object.
- Return type:
Example
>>> from gpx import read_kml >>> gpx = read_kml("path/to/file.kml")
gpx.utils Module¶
Utilities for GPX models.
This module provides utilities for automatic XML parsing and serialization based on dataclass field types and metadata.
Key GPX specification pattern: - XML attributes are always required → dataclass fields without | None - XML child elements are always optional → dataclass fields with | None
This allows automatic determination of attributes vs elements based on type hints.
- gpx.utils.extract_namespaces_from_string(xml_string)¶
Extract namespace prefix mappings from an XML string.
This function extracts all namespace declarations (xmlns attributes) from the XML string using regex, before ElementTree parsing which loses prefix info.
- gpx.utils.from_isoformat(dt_str)¶
Convert a string in ISO 8601 format to a datetime object.
- gpx.utils.to_isoformat(dt)¶
Convert a datetime object to a string in ISO 8601 format.
- gpx.utils.is_optional(field_type)¶
Check if a type annotation represents an optional field.
- gpx.utils.get_inner_type(field_type)¶
Extract the inner type from an Optional type annotation.
- gpx.utils.is_list_type(field_type)¶
Check if a type annotation represents a list.
- gpx.utils.get_list_item_type(field_type)¶
Extract the item type from a list type annotation.
- gpx.utils.has_from_xml(obj_type)¶
Check if a type has a from_xml classmethod.
- gpx.utils.has_to_xml(obj)¶
Check if an object has a to_xml method.
- gpx.utils.parse_from_xml(cls, element)¶
Parse XML element into dictionary by auto-detecting attributes vs elements.
Uses the GPX specification pattern: - Required fields (no | None) are parsed as XML attributes - Optional fields (with | None) are parsed as XML child elements
Supports: - Simple types (str, int, etc.) - Nested models (types with from_xml() method) - Lists of models (list[Model]) - Extensions (special handling for GPX extensions)
- gpx.utils.build_to_xml(obj, element, nsmap=None)¶
Serialize dataclass to XML by auto-detecting attributes vs elements.
Uses the GPX specification pattern: - Required fields (no | None) are serialized as XML attributes - Optional fields (with | None) are serialized as XML child elements
Supports: - Simple types (str, int, etc.) - Nested models (objects with to_xml() method) - Lists of models (list[Model])
- gpx.utils.has_geo_properties(obj, exclude_fields=None)¶
Check if a dataclass instance has any optional fields set (for GeoJSON properties).
This is used to determine whether a GeoJSON representation should be a pure geometry or a Feature with properties.
- gpx.utils.build_geo_properties(obj, exclude_fields=None)¶
Build a GeoJSON properties dictionary from a dataclass instance.
Converts dataclass fields to JSON-serializable values for GeoJSON properties. Excludes specified fields (typically coordinate fields) and only includes optional fields that are set.
- gpx.utils.build_geo_feature(geometry, obj, exclude_fields=None)¶
Build a GeoJSON Feature or pure geometry based on whether properties exist.
If the object has any optional fields set (excluding coordinate fields), returns a Feature with geometry and properties. Otherwise, returns the pure geometry.