Import GPX data to PostGIS

Here's how I imported geo data from a bunch of files containing GPS traces in GPX format into a PostGIS database for further analysis.

Assumptions

Install PostGIS

Golly, I recently wrote a tutorial how to install PostGIS - what a coincidence.

Install GDAL

GDAL is a "translator library for raster geospatial data formats". The important part is that it comes with a commandline tool to convert from one format to another, named ogr2ogr. We want that:

$ sudo port install gdal +postgresql91

Check that it works:

$ ogr2ogr --long-usage | grep PostgreSQL
-f "PostgreSQL"

Import data to PostgreSQL

Importing a single file using ogr2ogr is simple (and doesn't require the +postgresql variant above):

$ ogr2ogr -append -f PGDump /vsistdout/ gpx.jsp\?relation\=1076755 | psql DATABASE_NAME

Using find we can easily do it for multiple GPX files:

$ find . -name \*.gpx -exec ogr2ogr -append -f PostgreSQL "PG:dbname=DATABASE_NAME" {} \;

See if it worked

The following should return the number of files you've imported (I think - at least in my case it fit):

$ psql -d geo -c "SELECT COUNT(*) FROM routes"
 count
-------
   289
(1 row)

Happy geo-analysis!