Posts in the Programming category:

Drawing a GPX Track on a Map in Python

in Programming by evan power
Tags: , , ,

Programming in python is fun because you can do complex things relatively easy. Incredibly powerful libraries are just a 'pip install' away. Today I'll show you a quick example using a few such libraries to create a simple map with a GPS track drawn on it.

We will be using the GPXPY package to parse our gps track, and the Cartopy and Matplotlib packages do draw the underlying map and draw the GPS track on it.

We will be using Stamen Terrain map tiles.

First open a terminal emulator and type "pip install gpxpy matplotlib cartopy" You may need to add 'sudo' to the beginning of the 'pip install' command.

Run the code below. Set the trackFile variable so that it contains a path that points to the gpx file that you want to show on the map.

import gpxpy
import array
import matplotlib.pyplot as pyplot
import as crs
from import StamenTerrain

# Open and parse your GPX file.
trackFile = './pemberton.gpx'
track = gpxpy.parse(open(trackFile))
# Make an iterator over the points in the GPS track.
trackPoints = track.walk()
# Make empty arrays to put the latitudes an longitudes in.
lats = array.array('f')
lons = array.array('f')
# Iterate over all points an populate the latitude and longitude arrays.
for p in trackPoints:
# Get the minimum and maximum latitudes and longitudes from the GPS track.
bounds = track.get_bounds()
# Use the Stamen Terrain tile server
tiler = StamenTerrain()
fig = pyplot.figure(figsize=(5,5))
axes = pyplot.axes(
axes.set_extent([bounds.min_longitude, bounds.max_longitude,
                bounds.min_latitude, bounds.max_latitude])
zoom = 14
axes.add_image(tiler, zoom)

pyplot.plot(lons, lats, 'm-', transform=crs.Geodetic(), linewidth=2)

The output looks like this:


Easy peasy.

Thanks to th developers of Python, GPXPY, Cartopy, Matplotlib for their work, and thanks to the folks at Stamen for making their map tiles pretty an easy to use.