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>)¶
Bases:
GPXModelThe 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.
- to_xml(tag=None, nsmap=None)¶
Convert the GPX to an XML 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:
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.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.
- 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.
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.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.
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)¶
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.
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)¶
Bases:
GPXModelA 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 (dt.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.
- 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, rtept=<factory>)¶
Bases:
GPXModelAn 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.
rtept (list[Waypoint]) – List of route points. Defaults to empty list.
- property moving_duration: timedelta¶
The moving duration.
The moving duration is the total duration with a speed greater than 0.5 km/h.
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, trkseg=<factory>)¶
Bases:
GPXModelAn 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.
trkseg (list[TrackSegment]) – List of track segments. Defaults to empty list.
- 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.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>)¶
Bases:
GPXModelA 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.
- property moving_duration: timedelta¶
The moving duration.
The moving duration is the total duration with a speed greater than 0.5 km/h.
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.
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.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.remove_encoding_from_string(s)¶
Remove encoding declarations (e.g. encoding=”utf-8”) from the string, if any.
- 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])
- 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.