GPX

Keith Vetter - 2010-07-08 : To quote Wikipedia, GPX, or GPS eXchange Format is an XML schema designed as a common GPS data format for software applications.

It can be used to describe waypoints, tracks, and routes. The format is open and can be used without the need to pay license fees. Its tags store location, elevation, and time and can in this way be used to interchange data between GPS devices and software packages. Such computer programs allow users, for example, to view their tracks, project their tracks on satellite images (in Google Earth), annotate maps, and tag photographs with the geolocation in the Exif metadata.

Here's a package that parses and extracts waypoint, track, route and metadata information from an XML file. Documentation is in the code's header plus there's demo code at the end.

KPV 2010-07-08 : fixed an xpath error


##+##########################################################################
#
# gpx.tcl -- Parse gpx files
# by Keith Vetter, July 7, 2010
#
# gpx definition:
#   http://www.topografix.com/gpx.asp
#   http://www.topografix.com/GPX/1/1/
#   GPX 1.0 => http://www.topografix.com/gpx_manual.asp

# API
#  set token [::gpx::Create gpxFilename]
#  ::gpx::Cleanup $token
#  ::gpx::GetGPXMetadata $token               => dict of metadata
#  ::gpx::GetWaypointCount $token             => number of waypoints
#  ::gpx::GetAllWaypoints $token              => list of waypoint items
#  ::gpx::GetTrackCount $token                => number of tracks
#  ::gpx::GetTrackMetadata $token $whichTrack => dict of metadata for this track
#  ::gpx::GetTrackPoints $token $whichTrack   => list of trkpts for this track
#  ::gpx::GetRouteCount $token                => number of routes
#  ::gpx::GetRouteMetadata $token $whichRoute => dict of metadata for this route
#  ::gpx::GetRoutePoints $token $whichRoute   => list of rtepts for this route
#
# o metadata is a dictionary whose keys depends on the which optional elements
#   are present and whose structure depends on the element's schema
#
# o a waypoint/trackpoint is a 3 element list consisting of latitude,
#   longitude and a dictionary of metadata:
#   e.g. 41.61716028 -70.61758477 {ele 35.706 time 2010-06-17T16:02:28Z}
#

package require Tcl 8.5
package require tdom

namespace eval gpx {
    variable nameSpaces {
        gpx "http://www.topografix.com/GPX/1/1"
        xsi "http://www.w3.org/2001/XMLSchema-instance"
    }
    # gpx 1.0 was obsoleted August 9, 2004, but we handle it anyway
    variable nameSpaces10 {
        gpx "http://www.topografix.com/GPX/1/0"
        topografix "http://www.topografix.com/GPX/Private/TopoGrafix/0/2"
    }
    variable gpx
    set gpx(id) 0

    # Cleanup any existing doms if we reload this module
    ::apply {{} {
        foreach arr [array names ::gpx::gpx dom,*] {
            catch {$::gpx::gpx($arr) delete}
            unset ::gpx::gpx($arr)
        }
    }}
}

##+##########################################################################
#
# ::gpx::Create -- Creates a tdom object, returns opaque token to it
#  parameters: gpxFilename
#  returns: token for this tdom object
#
proc ::gpx::Create {gpxFilename {rawXML {}}} {
    variable nameSpaces
    variable gpx

    if {$rawXML eq ""} {
        set fin [open $gpxFilename r]
        set rawXML [read $fin] ; list
        close $fin
    }

    set token "gpx[incr gpx(id)]"
    dom parse $rawXML gpx(dom,$token)

    # Check version 1.0, 1.1 or fail
    set version [[$gpx(dom,$token) documentElement] getAttribute version 0.0]
    if {[package vcompare $version 1.1] >= 0} {
        $gpx(dom,$token) selectNodesNamespaces $::gpx::nameSpaces
    } elseif {[package vcompare $version 1.0] == 0} {
        $gpx(dom,$token) selectNodesNamespaces $::gpx::nameSpaces10
    } else {
        $gpx(dom,$token) delete
        error "$gpxFilename is version $version, need 1.0 or better"
    }
    set gpx(version,$token) $version
    return $token
}
##+##########################################################################
#
# ::gpx::Cleanup -- Cleans up an instance of a tdom object
#   parameter: token returned by ::gpx::Create
#
proc ::gpx::Cleanup {token} {
    variable gpx
    $gpx(dom,$token) delete
    unset gpx(dom,$token)
}


##+##########################################################################
#
# ::gpx::GetGPXMetadata -- Return metadata dictionary for entire document
#   parameter: token returned by ::gpx::Create
#   returns: metadata dictionary for entire document
#
proc ::gpx::GetGPXMetadata {token} {
    set gpxNode [$::gpx::gpx(dom,$token) documentElement]
    set version $::gpx::gpx(version,$token)
    set creator [$gpxNode getAttribute creator ?]
    set attr [dict create version $version creator $creator]

    if {[package vcompare $version 1.0] == 0} {
        set result [::gpx::_ExtractNodeMetadata $token $gpxNode]
    } else {
        set meta [$::gpx::gpx(dom,$token) selectNodes /gpx:gpx/gpx:metadata]
        set result [::gpx::_ExtractNodeMetadata $token $meta]
    }
    set result [dict merge $attr $result]
    return $result
}

##+##########################################################################
#
# ::gpx::GetWaypointCount -- Return number of waypoints defined in gpx file
#   parameter: token returned by ::gpx::Create
#   returns: number of waypoints
#
proc ::gpx::GetWaypointCount {token} {
    set wpts [$::gpx::gpx(dom,$token) selectNodes /gpx:gpx/gpx:wpt]
    return [llength $wpts]
}
##+##########################################################################
#
# ::gpx::GetAllWaypoints -- Returns list of waypoints, each item consists
# of {lat lon <dictionary of metadata>}
#   parameter: token returned by ::gpx::Create
#   returns: list of waypoint items
#
proc ::gpx::GetAllWaypoints {token} {
    set wpts [$::gpx::gpx(dom,$token) selectNodes /gpx:gpx/gpx:wpt]

    set result {}
    foreach wpt $wpts {
        set lat [$wpt getAttribute "lat" ?]
        set lon [$wpt getAttribute "lon" ?]
        set meta [::gpx::_ExtractNodeMetadata $token $wpt]
        lappend result [list $lat $lon $meta]
    }
    return $result
}
##+##########################################################################
#
# ::gpx::GetTrackCount -- returns how many tracks
#   parameter: token returned by ::gpx::Create
#   returns: number of tracks
#
proc ::gpx::GetTrackCount {token} {
    set trks [$::gpx::gpx(dom,$token) selectNodes /gpx:gpx/gpx:trk]
    return [llength $trks]
}
##+##########################################################################
#
# ::gpx::GetTrackMetadata -- Returns metadata dictionary for this track
#   parameter: token returned by ::gpx::Create
#              whichTrack: which track to get (1 based)
#   returns: metadata dictionary for this track
#
proc ::gpx::GetTrackMetadata {token whichTrack} {
    set trkNode [$::gpx::gpx(dom,$token) selectNodes \
                     /gpx:gpx/gpx:trk\[$whichTrack\]]

    set meta [::gpx::_ExtractNodeMetadata $token $trkNode]
}
##+##########################################################################
#
# ::gpx::GetTrackPoints -- Returns track consisting of a list of track points,
# each of which consists of {lat lon <dictionary of metadata>}
#   parameter: token returned by ::gpx::Create
#              whichTrack: which track to get (1 based)
#   returns: list of trackpoints for given track
#
proc ::gpx::GetTrackPoints {token whichTrack} {
    set trkpts [$::gpx::gpx(dom,$token) selectNodes \
                    /gpx:gpx/gpx:trk\[$whichTrack\]//gpx:trkpt]
    set result {}
    foreach trkpt $trkpts {
        set lat [$trkpt getAttribute "lat" ?]
        set lon [$trkpt getAttribute "lon" ?]
        set meta [::gpx::_ExtractNodeMetadata $token $trkpt]
        lappend result [list $lat $lon $meta]
    }
    return $result
}
##+##########################################################################
#
# ::gpx::GetRouteCount -- returns how many routes
#   parameter: token returned by ::gpx::Create
#   returns: number of routes
#
proc ::gpx::GetRouteCount {token} {
    set rtes [$::gpx::gpx(dom,$token) selectNodes /gpx:gpx/gpx:rte]
    return [llength $rtes]
}
##+##########################################################################
#
# ::gpx::GetRouteMetadata -- Returns metadata dictionary for this route
#   parameter: token returned by ::gpx::Create
#              whichRoute: which route to get (1 based)
#   returns: metadata dictionary for this route
#
proc ::gpx::GetRouteMetadata {token whichRoute} {
    set rteNode [$::gpx::gpx(dom,$token) selectNodes \
                     /gpx:gpx/gpx:rte\[$whichRoute\]]

    set meta [::gpx::_ExtractNodeMetadata $token $rteNode]
}
##+##########################################################################
#
# ::gpx::GetRoutePoints -- Returns route consisting of a list of route points,
# each of which consists of {lat lon <dictionary of metadata>}
#   parameter: token returned by ::gpx::Create
#              whichRoute: which route to get (1 based)
#   returns: list of routepoints for given route
#
proc ::gpx::GetRoutePoints {token whichRoute} {
    set rtepts [$::gpx::gpx(dom,$token) selectNodes \
                    /gpx:gpx/gpx:rte\[$whichRoute\]//gpx:rtept]
    set result {}
    foreach rtept $rtepts {
        set lat [$rtept getAttribute "lat" ?]
        set lon [$rtept getAttribute "lon" ?]
        set meta [::gpx::_ExtractNodeMetadata $token $rtept]
        lappend result [list $lat $lon $meta]
    }
    return $result
}
##+##########################################################################
#
# ::gpx::_ExtractNodeMetadata -- Internal routine to get all
# the optional data associated with an xml element. For most
# elements we just want element name and text value but some
# we want their attributes and some we want children metadata.
#
proc ::gpx::_ExtractNodeMetadata {token node} {
    set result {}
    if {$node eq ""} { return $result }

    # author and email elements are different in version 1.0 and 1.1
    set onlyAttributes [list "bounds" "email"]
    set attributesAndElements [list "extension" "author" "link" "copyright"]
    if {$::gpx::gpx(version,$token) == 1.0} {
        set onlyAttributes [list "bounds"]
        set attributesAndElements [list "extension" "link" "copyright"]
    }

    foreach child [$node childNodes] {
        set nodeName [$child nodeName]

        if {$nodeName in {"wpt" "trk" "trkseg" "trkpt" "rte" "rtept"}} continue
        if {[string match "topografix:*" $nodeName]} continue

        if {$nodeName in $onlyAttributes} {
            set attr [::gpx::_GetAllAttributes $child]
            lappend result $nodeName $attr
        } elseif {$nodeName in $attributesAndElements} {
            set attr [::gpx::_GetAllAttributes $child]
            set meta [::gpx::_ExtractNodeMetadata $token $child]
            set meta [concat $attr $meta]
            lappend result $nodeName $meta
        } else {
            lappend result $nodeName [$child asText]
        }
    }
    return $result
}
##+##########################################################################
#
# ::gpx::_GetAllAttributes -- Returns dictionary of attribute name and value
#
proc ::gpx::_GetAllAttributes {node} {
    set result {}
    foreach attr [$node attributes] {
        lappend result $attr [$node getAttribute $attr]
    }
    return $result
}
################################################################

#
# simple test code
#

set rawXML {<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" creator="Oregon 400t" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd">
  <metadata>
    <link href="http://www.garmin.com">
      <text>Garmin International</text>
    </link>
    <time>2009-10-17T22:58:43Z</time>
  </metadata>
  <trk>
    <name>Example GPX Document</name>
    <trkseg>
      <trkpt lat="47.644548" lon="-122.326897">
        <ele>4.46</ele>
        <time>2009-10-17T18:37:26Z</time>
      </trkpt>
      <trkpt lat="47.644548" lon="-122.326897">
        <ele>4.94</ele>
        <time>2009-10-17T18:37:31Z</time>
      </trkpt>
      <trkpt lat="47.644548" lon="-122.326897">
        <ele>6.87</ele>
        <time>2009-10-17T18:37:34Z</time>
      </trkpt>
    </trkseg>
  </trk>
</gpx>
}
lassign $argv gpxFilename
if {$gpxFilename ne ""} {
    set token [::gpx::Create $gpxFilename]
} else {
    set token [::gpx::Create "" $rawXML]
}

# Display document's metadata
set docMeta [::gpx::GetGPXMetadata $token]
dict for {key value} $docMeta {
    puts "  $key => $value"
}
puts ""

# Display waypoint info
set wpts [::gpx::GetAllWaypoints $token]
set min [set max ?]
foreach wpt $wpts {
    set wptDict [lindex $wpt 2]
    if {! [dict exists $wptDict ele]} continue
    set ele [dict get $wptDict ele]
    if {$max eq "?"} { set min [set max $ele]}
    set max [expr {max($max,$ele)}]
    set min [expr {min($min,$ele)}]
}
puts "Waypoints: [::gpx::GetWaypointCount $token]"
puts "  highest: $max meters"
puts "   lowest: $min meters"

# Display track info
set trkCnt [::gpx::GetTrackCount $token]
puts "Tracks: $trkCnt"
for {set i 1} {$i <= $trkCnt} {incr i} {
    set trackMeta [::gpx::GetTrackMetadata $token $i]
    set trk [::gpx::GetTrackPoints $token $i]
    puts "  track $i:"
    dict for {key value} $trackMeta {
        puts "    $key => $value"
    }
    puts "    trackpoints: [llength $trk]"
}
# Display route info
set rteCnt [::gpx::GetRouteCount $token]
puts "Routes: $rteCnt"
for {set i 1} {$i <= $rteCnt} {incr i} {
    set routeMeta [::gpx::GetRouteMetadata $token $i]
    set rte [::gpx::GetRoutePoints $token $i]
    puts "  route $i:"
    dict for {key value} $routeMeta {
        puts "    $key => $value"
    }
    puts "    routepoints: [llength $rte]"
}
if {$tcl_interactive} return
::gpx::Cleanup $token
return