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: GeoGPXModel

The 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.

  • rte (list[Route]) – List of routes. Defaults to empty list.

  • trk (list[Track]) – List of tracks. 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:

Element

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:

str

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:
  • file_path (str | Path) – The file path to write the GPX data to.

  • pretty_print (bool) – Whether to format the output with indentation. Defaults to True.

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:
  • file_path (str | Path) – The file path to write the GeoJSON data to.

  • indent (int | None) – Indentation level for pretty printing. Defaults to 2.

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:
  • file_path (str | Path) – The file path to write the KML data to.

  • pretty_print (bool) – Whether to format the output with indentation. Defaults to True.

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:

str

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:

bytes

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: GPXModel

Information 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: GeoGPXModel

A 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).

Parameters:
  • other (Waypoint) – The other waypoint.

  • radius (int) – The radius of the earth. Defaults to 6,378,137 metres.

Returns:

The distance to the other waypoint (in metres).

Return type:

float

duration_to(other)

Return the duration to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The duration to the other waypoint. Returns zero dt.timedelta if either waypoint lacks a timestamp.

Return type:

timedelta

speed_to(other)

Return the speed to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The speed to the other waypoint (in metres per second). Returns 0.0 if either waypoint lacks a timestamp or both share the same timestamp (i.e. duration is zero).

Return type:

float

gain_to(other)

Return the elevation gain to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The elevation gain to the other waypoint (in metres). Returns zero if either waypoint lacks elevation data.

Return type:

Decimal

slope_to(other)

Return the slope to another waypoint.

Parameters:

other (Waypoint) – The other waypoint.

Returns:

The slope to the other waypoint (in percent). Returns 0 if the two waypoints share the same coordinates (i.e. distance is zero).

Return type:

Decimal

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, GeoGPXModel

An 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, GeoGPXModel

An 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 total_distance: float

The total distance of the track (in metres).

property total_duration: timedelta

The total duration of the track (in seconds).

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.

property max_speed: float

The maximum speed of the track (in metres / second).

property min_speed: float

The minimum speed of the track (in metres / second).

property speed_profile: list[tuple[datetime, float]]

The speed profile of the track.

The speed profile is a list of (timestamp, speed) tuples.

property total_ascent: Decimal

The total ascent of the track (in metres).

property total_descent: Decimal

The total descent of the track (in metres).

property elevation_profile: list[tuple[float, Decimal]]

The elevation profile of the track.

The elevation profile is a list of (distance, elevation) tuples. Distance accumulates within each segment but does not include the gap between consecutive segments.

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: object

Container 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.

Parameters:

elements (list[Element]) – List of XML elements from extension namespaces.

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:

Extensions

find(path, namespaces=None)

Find a child element using XPath.

Searches through all top-level extension elements for a matching descendant.

Parameters:
  • path (str) – XPath expression (e.g., “gpxtpx:TrackPointExtension/gpxtpx:hr”).

  • namespaces (dict[str, str] | None) – Namespace prefix mapping (e.g., {“gpxtpx”: “http://…”}).

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.

Parameters:
  • path (str) – XPath expression.

  • namespaces (dict[str, str] | None) – Namespace prefix mapping.

Returns:

List of all matching elements.

Return type:

list[Element]

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:
  • tag (str) – The element tag name (local name, without namespace prefix).

  • namespace (str | None) – The namespace URI. If None, searches all namespaces.

  • default (str | None) – Default value if element not found or has no text.

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:
  • tag (str) – The element tag name.

  • namespace (str | None) – The namespace URI. If None, searches all namespaces.

  • default (int | None) – Default value if element not found or conversion fails.

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:
  • tag (str) – The element tag name.

  • namespace (str | None) – The namespace URI. If None, searches all namespaces.

  • default (float | None) – Default value if element not found or conversion fails.

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.

Parameters:
  • tag (str) – The element tag name.

  • namespace (str | None) – The namespace URI. If None, matches any namespace.

Returns:

True if an element was removed, False otherwise.

Return type:

bool

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.

Parameters:

elements (list[Element]) – List of XML elements to append.

get_namespaces()

Get all namespaces used in extension elements.

Returns:

Set of namespace URIs.

Return type:

set[str]

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:

Extensions

to_xml(tag=None, nsmap=None)

Convert to an XML <extensions> element.

Parameters:
  • tag (str | None) – The XML tag name. Defaults to “extensions”.

  • nsmap (dict[str | None, str] | None) – Namespace mapping. Defaults to GPX 1.1 namespace.

Returns:

The XML element containing all extension elements.

Return type:

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, GeoGPXModel

A 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.

class gpx.copyright.Copyright(author, *, year=None, license=None)

Bases: GPXModel

Information about the copyright holder and any license.

By linking to an appropriate license, you may place your data into the public domain or grant additional usage rights.

Parameters:
  • author (str) – Copyright holder (e.g. TopoSoft, Inc.)

  • year (int | None) – Year of copyright. Defaults to None.

  • license (str | None) – Link to external file containing license text. Defaults to None.

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.

class gpx.email.Email(id, domain)

Bases: GPXModel

An email address.

Broken into two parts (id and domain) to help prevent email harvesting.

Parameters:
  • id (str) – id half of email address (e.g. billgates2004)

  • domain (str) – domain half of email address (e.g. hotmail.com)

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.

class gpx.person.Person(*, name=None, email=None, link=None)

Bases: GPXModel

A person or organization.

Parameters:
  • name (str | None) – Name of person or organization. Defaults to None.

  • email (Email | None) – Email address. Defaults to None.

  • link (Link | None) – Link to Web site or other external information about person. Defaults to None.

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: GeoGPXModel

Two lat/lon pairs defining the extent of an element.

Parameters:
  • minlat (Latitude) – The minimum latitude.

  • minlon (Longitude) – The minimum longitude.

  • maxlat (Latitude) – The maximum latitude.

  • maxlon (Longitude) – The maximum longitude.

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.

as_tuple()

Return the bounds as a tuple.

Returns:

A tuple of (minlat, minlon, maxlat, maxlon).

Return type:

tuple[Latitude, Longitude, Latitude, Longitude]

gpx.types Module

This module provides simple type objects to contain various GPX data.

class gpx.types.SupportsGeoInterface(*args, **kwargs)

Bases: Protocol

class gpx.types.Latitude(value)

Bases: Decimal

A latitude class for the GPX data format.

The latitude of the point. Decimal degrees, WGS84 datum.

Parameters:

value (str | float | Decimal) – The latitude value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [-90.0, 90.0]).

class gpx.types.Longitude(value)

Bases: Decimal

A longitude class for the GPX data format.

The longitude of the point. Decimal degrees, WGS84 datum.

Parameters:

value (str | float | Decimal) – The longitude value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [-180.0, 180.0]).

class gpx.types.Degrees(value)

Bases: Decimal

A degrees class for the GPX data format.

Used for bearing, heading, course. Units are decimal degrees, true (not magnetic).

Parameters:

value (str | float | Decimal) – The degrees value.

Raises:

ValueError – If the value is not a valid latitude (i.e. between [0.0, 360.0)).

class gpx.types.Fix(value)

Bases: str

A 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: int

A DGPS station class for the GPX data format.

Represents a differential GPS station.

Parameters:

value (int | str) – The DGPS station value.

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: object

Base 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.

_tag

The default XML tag name for this model.

Type:

ClassVar[str]

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:

Self

to_xml(tag=None, nsmap=None)

Convert the model to an XML element.

Parameters:
  • tag (str | None) – The XML tag name. Defaults to the model’s _tag attribute.

  • nsmap (dict[str | None, str] | None) – Optional namespace mapping. Defaults to GPX 1.1 namespace.

Returns:

The XML element.

Return type:

Element

class gpx.base.GeoGPXModel

Bases: GPXModel, ABC

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 via isinstance() and type hints.

gpx.mixins Module

This module provides mixin classes.

class gpx.mixins.PointsMixin

Bases: object

A 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. Track iterates segments while Route / TrackSegment iterate 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 total_distance: float

The total distance (in metres).

property total_duration: timedelta

The total duration.

property moving_duration: timedelta

The moving duration.

The moving duration is the total duration with a speed greater than 0.5 km/h.

property avg_speed: float

The average speed (in metres / second).

property avg_moving_speed: float

The average moving speed (in metres / second).

property max_speed: float

The maximum speed (in metres / second).

property min_speed: float

The minimum speed (in metres / second).

property speed_profile: list[tuple[datetime, float]]

The speed profile.

The speed profile is a list of (timestamp, speed) tuples.

property avg_elevation: Decimal

The average elevation (in metres).

property max_elevation: Decimal

The maximum elevation (in metres).

property min_elevation: Decimal

The minimum elevation (in metres).

property diff_elevation: Decimal

The difference in elevation (in metres).

property total_ascent: Decimal

The total ascent (in metres).

property total_descent: Decimal

The total descent (in metres).

property elevation_profile: list[tuple[float, Decimal]]

The elevation profile.

The elevation profile is a list of (distance, elevation) tuples.

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:

GPX

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:

GPX

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:
  • wkb (bytes) – WKB as bytes.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Raises:

ValueError – If the WKB format is invalid or geometry type is unsupported.

Return type:

GPX

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:
  • wkt (str) – WKT string.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Raises:

ValueError – If the WKT format is invalid or geometry type is unsupported.

Return type:

GPX

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:

file_path (str | Path) – Path to the GPX file.

Returns:

A GPX object with namespace prefixes preserved.

Return type:

GPX

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:
  • file_path (str | Path) – Path to the GeoJSON file.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Return type:

GPX

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:
  • file_path (str | Path) – Path to the KML file.

  • creator (str | None) – The creator string for the GPX. Defaults to None (uses default).

Returns:

A GPX object.

Return type:

GPX

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.

Parameters:

xml_string (str) – The XML string to extract namespaces from.

Returns:

A dictionary mapping namespace prefixes to URIs. The default namespace (if present) is mapped to the empty string key.

Return type:

dict[str, str]

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.

Parameters:

field_type (type) – The type annotation to check.

Returns:

True if the type is Optional (Union[T, None]), False otherwise.

Return type:

bool

gpx.utils.get_inner_type(field_type)

Extract the inner type from an Optional type annotation.

Parameters:

field_type (type) – The type annotation (possibly Optional).

Returns:

The inner type (without None).

Return type:

type

gpx.utils.is_list_type(field_type)

Check if a type annotation represents a list.

Parameters:

field_type (type) – The type annotation to check.

Returns:

True if the type is a list, False otherwise.

Return type:

bool

gpx.utils.get_list_item_type(field_type)

Extract the item type from a list type annotation.

Parameters:

field_type (type) – The list type annotation.

Returns:

The item type.

Return type:

type

gpx.utils.has_from_xml(obj_type)

Check if a type has a from_xml classmethod.

Parameters:

obj_type (type) – The type to check.

Returns:

True if the type has a from_xml method, False otherwise.

Return type:

bool

gpx.utils.has_to_xml(obj)

Check if an object has a to_xml method.

Parameters:

obj (Any) – The object to check.

Returns:

True if the object has a to_xml method, False otherwise.

Return type:

bool

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)

Parameters:
  • cls (type[Any]) – The dataclass type.

  • element (Element) – The XML element to parse.

Returns:

A dictionary mapping field names to parsed values.

Raises:

ValueError – If a required attribute is missing.

Return type:

dict[str, Any]

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])

Parameters:
  • obj (Any) – The dataclass instance.

  • element (Element) – The XML element to populate.

  • nsmap (dict[str | None, str] | None) – Optional namespace mapping for child elements.

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.

Parameters:
  • obj (Any) – The dataclass instance to check.

  • exclude_fields (Iterable[str] | None) – Field names to exclude from the check (e.g., coordinate fields).

Returns:

True if any optional fields (excluding specified ones) are set, False otherwise.

Return type:

bool

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.

Parameters:
  • obj (Any) – The dataclass instance.

  • exclude_fields (Iterable[str] | None) – Field names to exclude (e.g., coordinate fields).

Returns:

A dictionary mapping field names to JSON-serializable values.

Return type:

dict[str, Any]

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.

Parameters:
  • geometry (dict[str, Any]) – The GeoJSON geometry dictionary.

  • obj (Any) – The dataclass instance.

  • exclude_fields (Iterable[str] | None) – Field names to exclude from properties (e.g., coordinate fields).

Returns:

A GeoJSON Feature or pure geometry dictionary.

Return type:

dict[str, Any]