Skip to content

How To: Create

Vincent Neo edited this page Feb 19, 2021 · 1 revision

How to create?

You will first start off with a GPXRoot.

Initializing GPXRoot

let root = GPXRoot(creator: "Your app name here!") // insert your app name here

Now, you can start adding things to your GPXRoot. This includes your metadata, waypoints, tracks, routes, as well as extensions(if any).

Adding waypoints to GPXRoot

root.add(waypoints: arrayOfWaypoints) // adds an array of waypoints
root.add(waypoint: singleWaypoint)    // adds a single waypoint

Adding tracks to GPXRoot

root.add(tracks: arrayOfTracks)       // adds an array of tracks
root.add(track: singleTrack)          // adds a single track

Adding routes to GPXRoot

root.add(routes: arrayOfRoutes)       // adds an array of routes
root.add(route: singleRoute)          // adds a single route

Adding metadata to GPXRoot

let metadata = GPXMetadata()
metadata.name = "Your Name Here"
metadata.desc = "Description of your GPX file"
root.metadata = metadata              // adds metadata stuff

Example of application of GPXRoot

let root = GPXRoot(creator: "Your app name here!")
var trackpoints = [GPXTrackPoint]()

let yourLatitudeHere: CLLocationDegrees = 1.3521
let yourLongitudeHere: CLLocationDegrees = 103.8198
let yourElevationValue: Double = 10.724

let trackpoint = GPXTrackPoint(latitude: yourLatitudeHere, longitude: yourLongitudeHere)
trackpoint.elevation = yourElevationValue
trackpoint.time = Date() // set time to current date
trackpoints.append(trackpoint)

let track = GPXTrack()                          // inits a track
let tracksegment = GPXTrackSegment()            // inits a tracksegment
tracksegment.add(trackpoints: trackpoints)      // adds an array of trackpoints to a track segment
track.add(trackSegment: tracksegment)           // adds a track segment to a track
root.add(track: track)                          // adds a track

print(root.gpx())				// prints the GPX formatted string

This would be what you get from root.gpx() in the above example:

<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="Your app name here!">
	<trk>
		<trkseg>
			<trkpt lat="1.352100" lon="103.819800">
				<ele>10.724</ele>
				<time>2019-02-12T05:38:19Z</time>
			</trkpt>
		</trkseg>
	</trk>
</gpx>
  • .gpx() of GPXRoot outputs a String which can then be packaged as a .GPX file.
  • .OutputToFile(saveAt:fileName:) directly saves GPX contents to a URL specified.