Some Bits: Nelson's log

13 posts about qgis

Simple GeoTIFF overlay map

Spent some time today trying to display a historical aerial photo in a map context. Here’s some notes on using QGIS and Felt.

Someone told me about UCSB’s aerial image archive. It’s remarkable: a large collection of historical aerial photographs, many free of charge. All georeferenced on a tool called FrameFinder and easily downloadable. So I found one from 1952 that covers the area my house is in and wanted to put it on a map. Not too hard but not easy.

Georeferencing

The FrameFinder images aren’t GeoTIFFs, they have no spatial data. So first I used the QGIS georeferencer to get them on a map. The source images are very nicely scanned and taken, I suspect they are true straight down images. Even so I put down about 12 control points on road intersections by reference to Google Satellite imagery. Then I used the Projective transform to warp it; it ended up slightly angling the source image. Important to set the “transparency is 0” option so the border of the warped image doesn’t obscure things!

I wish the QGIS georeferencer were more nicely interactive.

QGIS

With the image georeferenced it was very simple to load it as a layer in a QGIS map. I tried a bunch of different ideas for a base map to reference to. I finally settled on MapTiler’s plugin, their Toner layer is a nicely styled vector map that you can plop on top of a raster image like mine. I customized the symbols: removing most of the polygon fills, turning rivers blue, etc. The result looks OK.

The other thing I did was use the Google Satellite layer in the background. Normally it’s obscured entirely by the older aerial photo but you can easily toggle that off and on to do a quick before-and-now comparison.

An aside: every time I do something new in QGIS I start by just hacking something up loading data from any-old-place, often my browser Downloads folder. Then I have to do extra work to rebuild the project with the files in a permanent place. Would be better to always put all the assets in one place first before working with QGIS.

Felt

I also gave Felt a try, a nice mapping startup. They have a really great tool that makes it easy to make custom maps with some light GIS work and styling. Drop a GeoTIFF on the map, select Roads and Buildings as vector layers on top, and you’re basically done.

Hit a bummer though: everything was looking good and I was ready to share it, then I reloaded and got a big “Paid plan required” overlay. I had hoped something this simple would be in the purview of their free plan but I think maybe adding a single custom image like mine puts me over. Felt a bit like a bait-and-switch, it letting me work for an hour+ before learning I’d have to pay. Not sure this one map is worth paying $30/mo to share but I have a bigger project in mind that would warrant the expense. Felt’s product is really nice and it’s all so fast!

MapWarper

For a third shot I made a version in Map Warper. This worked great. The control point UI in the rectifier is very nice and easy to use. The whole site is so tight, really easy. And there’s a nice preview mode with a simple transparency slider. The site is more of a tool for rectifying TIFFs, I think it’d be neat if it were enhanced to be more of a publishing site itself. That’d imply some hosting and serving costs though.

Something custom?

I feel like there’s room for a very simple “before and after” map webapp that takes a GeoTIFF and displays it against a basemap. With a toggle or slider or lens or something to let you see the old image and what it looks like now. I could probably cobble up something basic in a few hours. Hosting the GeoTIFF is the hard part although if you don’t bother to cut it into tiles it’s not too much. The closest I’ve found is GeoTIFF.io.

QGIS fun with LIDAR data

After fooling around with DEM data yesterday my buddy Mike did some nice work for me and gave me LIDAR data. Nnot raw LIDAR data but rather processed data; gridded DEMs of various sorts. The raw data comes from an August 2018 LIDAR survey of my area. I’m no expert at LIDAR at all but I learned enough to be dangerous, so here it is.

The raw data comes in LAZ files, which are basically point readings; a laser reflected off of something at that specific XYZ. Mike’s Makefile munges that through las2las, las2ogr, and ogr2ogr to get it into a specific reprojected GeoPackage file. Then gdal_grid does the real magic of looking at all those random points in XY space and mapping them to a uniform XY grid suitable for a raster DEM. From there you can use normal DEM tools.

The neat thing is LIDAR gives you multiple Z values for a specific X, Y coordinates. Ie: that there were reflections for a particular spot at, say, both 2103.37 meters and 2122.93 meters. What could that mean? In a word, trees. Sometimes the laser penetrates the leaves and reflects off the ground, sometimes it bounces off the leaves. That sounds noisy, but it’s super useful.

The trick is if you take the minimum elevation at every X, Y then you get a DEM of something like ground level. Not exactly; buildings will show higher, so will the middle of a tree trunk. But it’s pretty close. Similarly if you take the maximum then you get the height of the tree at that spot. And if you take the difference max-min you get the tree height. More or less.

So that’s what’s shown on my map above; tree heights from 0m to 25m rendered white to green. Isn’t that neat? The choice of 25m is important; too low and all the trees look the same, too high and you can’t see all of the forest for trying to emphasize the one tree.

A quick Google Search suggests it’s possible to write a tree classifier that looks solely at LIDAR data and knowledge about the biome and estimates a tree inventory by species. Helps if you can compare summer and winter images.

I tried also using a discrete color scale to color the tree height in categories. Flat ground (white), low brush (brown), small trees (light green), and big trees (dark green). It sort of works, I think the data picture below is fairly accurate, but it’s also pretty hard to read. Also it doesn’t tell me anything about what I really need to know, which is where there’s brush underneath trees.

I also experimented with using the LIDAR data to make contours. Honestly the result isn’t better than what I got with the 1/3 a.s. DEM file. It’s much noisier and the extra accuracy doesn’t much help. LIDAR contours in red, DEM contours in grey. I suspect if you really want to get a proper elevation map from LIDAR data alone you need to work harder at smoothing the data and discarding errors.

QGIS fun with elevation data

My neighborhood association is assessing what we need to do for fire safety on a plot of land we own. I’ve been having fun in QGIS mapping various aspects of the land. Particularly like this abstract example:

That’s showing the lot boundary (purple), the river (blue), a trail (mauve), and a powerline (black). And then 1m contours in light grey. Not a great map for navigation, but it does a nice job showing the terrain contours. Also it’s just kind of abstractly pretty.

Couldn’t be easier to do this stuff. Grab NED 1/3 arc second data off the National Map. Crop that DEM to a small region in QGIS, then have QGIS calculate contours, and Bob’s your uncle. QGIS is such a powerful tool. And cheers to GDAL doing all the work underneath.

Mapping Enga Province

I just finished a fun project; making a couple of maps of Papua New Guinea’s for a friend’s academic book chapter. I’ve never really collaborated with someone this way for a print publication and it was a good experience. Also this may sound goofy but the audacity of mapping PNG was part of the appeal; it’s a famously unmapped place.

The main map is a regional overview of Enga Province, in the PNG highlands. Also a detail map of the Porgera Valley area; the mine and various villages. Enga is not huge; 4500 square miles, a bit smaller than Connecticut, and with 432,000 people. It’s also very remote and mountainous and very thick with vegetation. It’s in that part of PNG that’s classic “uncontacted tribes” territory, although that was all 50+ years ago and a lot of folks there now have cell phones and Facebook. (David Attenborough’s A Blank on the Map is fun for the flavor, although it’s a different part of PNG.)

Online maps are pretty limited, but there are some beautiful paper maps going back to ground surveys in the 40s to 60s. To give you an idea of how limited digital maps are, here’s Google, Bing, and OSM. (They do get a bit better if you zoom in to the population centers like Wabag and Porgera.)

So my job was to produce an overview map of Enga to help readers orient to places named in the text. Also a detailed schematic view of Porgera. High res copies are available here.

Data: OSM and SRTM

The first challenge was getting data. The key things I wanted to draw were roads, rivers, and settlement locations. Secondarily I wanted to convey the terrain somehow, and for the Porgera area also map specific features related to the mine.

I went through a lot of data sources; Natural Earth, PNG government data, academic datasets, random shapefiles that fell off the back of a truck. Most of it proved not very good: incomplete, or old, or limited. Some exceptions though; the PNG government has a great dataset for the names of rivers, for instance.

I ended up mostly using OpenStreetMap data for rivers and roads. Several people have done a lot of excellent work mapping very detailed specifics of Enga Province; the street map of Paiam is a thing of beauty. The rivers were a bit spotty, I think there may have been some data loss at some point in OSM’s history. But the data was a comprehensive, uniform collection and I could fill in a few missing rivers with data from the Humanitarian Data Exchange. (I’m very curious where their data came from!)

I got the OSM data itself from the French OSM extracts. Excellent simple data source, grouped by country. I imported the PBF directly into QGIS, no conversion. Working with its unusual schema is a bit awkward but once you get used to it it’s not so bad.

For settlements I couldn’t find a dataset anywhere that worked great. I ended up getting a list of placenames and rough locations from the author I was working for, then painstakingly placing the dots precisely in the center of each of what looked like the “right cluster of houses” on aerial imagery. I also went back to some of those old 60s maps for ideas of where things might be, lots of fun. A similar process was used for the mine maps, although it helps that other people had done similar maps so I was never trying to do unique original data work.

That leaves terrain. This part’s easy! SRTM v3 for the basic elevation data, colored by 500m contours. Then overlaid on top of that a greyscale hillshade (courtesy of Mike) blended with hard light. I like the result, although it’s a bit noisy for print. Looks great in color on a screen though. (Extra detail: a 2600m contour line from OpenDEM to highlight the limit of cultivation of staple food crops.)

Design

The visual design is the part I’m not entirely happy about; my skills are more with data wrangling than aesthetics. I mostly went with very basic choices where I could; plain Arial font, plain standard map symbology, etc. I’d say the result is “adequate” but not beautiful.

For inspiration I drew on this Wikipedia map of Hawai’i. This 2008 SVG map is a thing of beauty, frequently cited as good design for Wikipedia. For map symbols I borrowed ideas from Wikipedia’s map template SVG although I ended up diverging quite a bit. Drawing roads with casings sure turned out complicated.

One thing I learned more about; text halos or buffers. It’s common to make labels stand out against busy backgrounds by rendering the text in black with a small white outline. Or so I thought. Actually it works better if the outline is light grey with 50% or more opacity; the white/black is too contrasty. QGIS lets you create buffers for labels directly. If you need to do them yourself in HTML/CSS, something like -webkit-text-stroke: 1.5mm rgba(255,255,255,0.5) works.

Software: QGIS

I did the whole map from start to finish in QGIS, mostly version 3.14. QGIS has come a long way and I’m very impressed with it, particularly for an open source tool. The UI is mostly accessible and if you can’t figure out how to do something (like, say, smooth a polygon) you can find an answer online. It has some baffling UI choices, like moving a vertex of a polygon isn’t animated. Also some bugs and weird limitations. I never could figure out how to edit the colors in my legend, custom symbols just wouldn’t take. But QGIS has a lot of complexity and power in a fairly usable package.

My favorite thing with QGIS is how great it is for experimental mapping. Early on I just loaded every single data layer I could find. Six different sources for rivers, four for roads. A bunch of scanned paper TIFFs I’d georectified. 30+ layers for me to tinker with, overlay, all to figure out which data sources I’d really use in the end. Lots of fun.

The part that sucks in QGIS is the Print Composer. The main map editor is lovely and taking screenshots from its display works great. But the moment you want to export a precisely defined PDF or a large raster image, you need to use the Print Composer. The composer is also where you add things like titles, scale bars, legends, etc.

Most of the composer works OK but it’s clumsy. The real problem is it’s got a whole different renderer! And this renderer does very different things for labels. I must have misunderstood something fundamental about print scaling, because a label would be a tiny little thing on my edit map and then this huge blob of word on the print map. And because labels try very hard not to be on top of each other, there’s was an enormous amount of hand tweaking and verification and testing to get everything correct. (Also a couple of map layers of fake curved lines just so I could put text on them). Seriously I was pulling my hair out with labels. I gather this is always the case in mapmaking but the inconsistent rendering algorithms really makes it hard.

OSM and Wikipedia?

So now I’m done; map submitted to the author. For now. I’d guess I spend 50-80 hours on this project, although someone focussed and better at QGIS could have done it in under 20. I spent a lot of time learning things I didn’t need to, PNG is fascinating!

We’ve talked about having a goal of making maps for all the PNG provinces for Wikipedia. I’d like to do that and I’m pretty well set up for it. The main thing stopping me is Wikipedia culture. The last thing I want is to do a bunch of hard work and have some gatekeeper come in and invalidate all my work without even an explanation.

I went looking for Wikipedia mapping standards and didn’t get real far. This conventions page has useful guidance but I can’t tell if it’s authoritative; a lot of it hasn’t been updated meaningfully since 2012 or so. When you dig into the tutorials, etc for mapmakers a lot of it ends in 2008 with excellent guides written in French for Inkscape. Back then QGIS wasn’t really realistic, now it is. That or even a custom automated software render pipeline, no hand editing at all.

What I really need is a Wikipedia map mentor, someone to work with me to get that first submission right so my work is accepted. Either that or maybe I’ll just put the map I have now on the page and see what response it gets.

QGIS: drawing roads with lines in casings

Many maps follow a sort of standard for symbology where roads are drawn as brown-orange-red lines with black casings around them. Like this, from a Wikipedia style guide.

QGIS has almost no support for drawing lines with casings, as common as it is. It’s something of a right of passage for map makers to figure out how to do it. I think I figured it out finally but I’m not an expert; please correct me in comments if I need it. This StackOverflow question is also helpful.

The basic idea is to draw two lines; a thick black line, then the thinner orange line on top of it. That’s simple enough. But it’s subtle and if you do it wrong all sorts of ugly things can happen.

Part of what makes doing this hard is that in most GIS data sets, roads aren’t just one single line. Particularly in OSM data roads are many line objects that are separate, little segments of road, and they just happen to overlap / join up right. Those joints can look terrible if you draw things wrong, see below. Also the intersections between roads need special attention.

I should note up-front that it’s important to test your results in whatever output format you’re really going to use. The on-screen preview in QGIS looks nice. But if you use the layout manager to compose a print run, know that the layout manager renders differently than the preview. Worse you’re probably really rendering to PDF or SVG, so you really have to look at those output files. And if you care about print, well, print it; the printer will change the way it looks once again. Most of the screenshots here are going to be in the main QGIS edit / preview mode.

The simplest thing is to just style the lines for your roads with two overlapping lines , like this in the Symbol Selector. Note the order matters!

In this case I have the black line as 1mm and the orange line as 0.6mm. Something like this is available as a default symbol in QGIS, the “Topo Main Road”.

This mostly works, and you should try it first and see if it’s acceptable because it’s so simple. However if you look closely, you’ll see small errors in the black casing. Particularly for roads made of many line segments. You can fix some of these by fiddling with the cap style; “flat” on the black line and “square” on the orange line works best for me. Here’s what square/square looks like blown up to 4mm to exaggerate the problems:

Another drawback with this simple approach is you don’t have any control over road intersections. They can end up looking terrible.

The more complicated drawing option is to have two layers for roads; one for the casings and one for the orange lines. You don’t actually need two full GIS layers though, you can also just duplicate the line data in the symbology classifier. In this case I’m using an OSM PBF extract with a Rule-Based Layer. (You might also be able to do this with a Categorized layer, but that type is less amenable to having multiple symbols for one type of data.)

If you just try this straight it might or might not work. The problem is that the order of these lines is not consistent in QGIS; they don’t necessarily draw in the order you have the rules in. To fix that you have to enable symbol levels (more info). This lets you specify the z-order of the symbols to control what order they are drawn in. Higher numbered levels are drawn on top of lower levels.

Note I’ve added in some extra complexity here; multiple sizes of roads. The general rule is you want to draw small roads first and then bigger roads on top of them. So the primary road is given the highest level, 15, so it draws on top of secondary and tertiar.

In this case I drew the casings right before the roads; doing things in that order makes it so the primary road has an uninterrupted casing. Here’s a sample of some roads of different sizes blown up to exaggerate the lines. (And the glitches in the casings, sigh. It looks better at normal resolution.)

Another option is to draw all the casings last, after all the roads. (Ie: have secondary’s orange line higher priority than the primary casing.) Doing that results in something that looks like this:

I’m not actually certain which is correct. I like the former better, so I’m doing that. Google Maps and the beautiful hand-rendered maps by Imus Geographics do the latter, so maybe I’m wrong. Honestly at normal map sizes you’d need a magnifying glass to see the difference.

One last note: symbol levels seem to only be relevant within their map layer. A symbol with a high level but in a lower map layer will not overdraw a symbol in a higher map layer.

So there you have it, roads with casings. And imperfections. I don’t know if it’s possible to actually do better in QGIS; I should really ask an expert. I sure wish QGIS just had support for “line with casing” as a symbol style. The “topo road” thing doesn’t cut it.

QGIS: drawing elevation increments

I wanted to make a map where every 100m of altitude has a different color. Ie: not a continuous ramp, but discrete colors. This turned out to be tricky enough I’m writing note.

1. Import DEM data like SRTM

2. Set the render style to “singleband pseudocolor”. Do not use “singleband grey”; it does not have the options we need.

3. set min / max to reasonable values. Ie 0 to 4000 meters. Set color interpolation to Discrete, pick a color ramp you like. (see step 7 for more)

4. Set mode to “Equal Interval”. Change the number of classes as you see fit; I chose 8. Click the “Classify” button.

5. Apply the style. It should look close to the result you want.

6. Tweak the Brightness / Saturation / Contrast to modify the overall effect as you need.

7. Experiment with different color maps. There’s a lot more built in than you’d think; if you “Create new color ramp” of type “Catalog: cpt-city” you find a lot of interesting options including many that are specifically for topography.

Here’s a simple brown every 500 meters scale I’m using.

The result looks like this (along with blue river lines from another data layer)

BTW the color map for my favorite Wikipedia map ever is one of the ones built in to QGIS. Or at least something similar. Look for “wiki-france” under “topography and bathymetry”.

QGIS 3.14: where the fuck am I?

I just spent 30 minutes trying to figure out how to figure out where I was on a QGIS map. Specifically I wanted to be able to click on the map and copy the coordinates. The way to do this has changed in various QGIS versions so old docs are wrong. QGIS 3.14 (the new hotness) just changed it again.

Bottom line: install the QGIS Coordinate Capture plugin from the plugin repo. It’s at version 0.2 right now. Then select the hand tool (the pan tool) and right click on the map. A little option to copy the coordinate will pop up along with a chooser for which CRS you want. Note you have to be in the hand tool: the Identify Features tool doesn’t have it.

The confusion at the moment is because the Coordinate Capture function was removed in 3.14. The discussion looks well meaning, someone refactoring functionality and saying “this should be reimplemented in a nicer way”. Only instead of first shipping the nicer way they just removed the old way and then called it a day. The worst kind of open source fuckery.

That change means the method in the 3.10 docs doesn’t work; there’s no longer a Coordinate Capture panel. Nor is there a toolbar as some docs reference. Nor does it show up in “Derived” under Identify Features as some QGIS2 docs suggest. Apparently this really fundamental feature has moved around a lot over the years. This plugin seems like a temporary hack, I suspect the method will change again soon.

OSM data in QGIS for simple print maps

I’ve been wanting to make some print maps in QGIS using OSM data for roads. There’s a bunch of ways to do this from simple to complex, but I think I found a way that works for me.

  • Start with an OSM extract in .osm.pbf format. These are produced daily for countries and regions and are manageable size.
  • Import it as a layer into QGIS, which has native support for .osm.pbf format. However it will be slow because it is not indexed.
  • Convert to GeoPackage in QGIS, with the defaults. All the property names, etc will be carried over and you’ll get a spatial index.
  • Use the new GeoPackage layer in your maps, you can delete the old OSM PBF layer entirely.

The main drawback is you’re dealing with OSM schema. Ie, drawing roads involves deciphering all the possible tag values for “highway”. It’d be nice to use some processed dataset converted to a simpler schema but I don’t know of an easy way to get a free one.

If you don’t care about licensing, MapTiler has some very nice OSM Planet tiles you can easily import in new versions of QGIS using their MapTiler QGIS Plugin. You can import these as raster maps or vectors. The vectors come with some schema translation and styling so you start with an OSM-looking map right there in QGIS and then modify it as you wish. The downside is I’m not sure you can use this data for, say, a print project without a licensing agreement from MapTiler. Also I didn’t see any easy way to control the level of detail so if you want to override their idea of feature selection at a zoom level you may be out of luck.

QGIS install on Mac

It takes roughly 60 UI actions to install QGIS on a Mac. And then you only get QGIS 2.0, not the latest 2.2. The problem is the official install is KyngChaos’ packages. They’ve done a great job over the years packaging Python and GIS software for Macs, but it’s seriously old school stuff. 4 different framework libraries have to be installed first by hand, each one individually packaged in a PKG installer script inside a DMG, then you install QGIS itself. Each installer takes many mouse clicks to install and also requires the root password.

In some sense KyngChaos is doing this right; the libraries he installs are useful for other projects, and this way you see all the license and components. But it’s really user unfriendly. It’d be nice if someone built a single self-contained QGIS.app that could just be dragged and run anywhere.

A second try at Ponoko for my walks

Giving a second try at using Ponoko for my walking tracks after this moderate success. Sha and Rachel of Meshu suggested etching the actual GPS traces on top of the blob, which I thought was clever. So here’s what I’m doing step by step.

1. Create a view for my tracks with simplification

CREATE OR REPLACE VIEW simple_tracks AS
 SELECT tracks.ogc_fid, st_simplify(tracks.wkb_geometry, 0.0002) AS wkb_geometry, tracks.name
   FROM tracks;

2. Use QGIS to make a map of all those tracks, then use “Save as Image” to get a PNG raster image. I made the lines of the tracks be 1mm solid black and zoomed in. Note QGIS exports the image at the size visible on screen, so make that window big first!

 

 

3. Use Pixelmator as a paint program to calculate the concave hull of all my walks. Basically I did a flood fill of the background of the image to some random color, then selected all the pixels of that flood fill color, then inverted the selection. Now my selection is my concave hull! I then used a black brush to fill in the selection so I have a basically monochrome image, also erased some hanging bits to have a cleaner shape. This is the step I wish I could just use ST_ConcaveHull() in PostGIS to do, or some other topology algorithm.

4. Convert the raster blob into a path. Load the painted image into Inkscape, choose Path / Trace Bitmap, and use the default Brightness cutoff. Click “OK”. Nothing visible happens, but now if you move the raster out of the way you’ll see there’s a second black shape. This one is a vector object. Edit the style so it has no fill and a black outline, just to make it obvious.

5. Create a new Inkscape document from the Ponoko starter kit.

6. Copy and paste my outline from step 4 into the new document, then update the stroke style to a cutting line (0.01mm, #0000ff). Note the caution about XQuartz and the Mac clipboard not copying vector objects.

7. Reload my GPS tracks into QGIS. Be careful to load the simplified tracks, for fewer points. Then use the QGIS Print Composer to save the map as an SVG. That tool is really confusing, basically you use the “add map” button to swipe out a rectangle on the page. Scale and centering doesn’t much matter, all we really want is the SVG bits.

8. Load the QGIS generated tracks SVG into Inkscape. Break the group and select the hairball of individual tracks. Copy and paste it into the main document from step 6. Adjust the style of the track hairballs to a light engraving line (0.01mm, #ff00ff). Then, the sadness, scale and align the track hairballs so they just match the outline from step 6. Visual process, non-exact, we’ll see how it looks.

9. Save the SVG and send to Ponoko!

This took me a couple of hours. All this paint program fiddling is terrible; the right thing is to do this all with code. Calculate that concave hull, dump it as SVG. Calculate the union of simplified tracks, clip it to fit inside the concave hull, dump it also as SVG. Combine with the same reference and done! PostGIS has an ST_AsSVG that helps, but until I can get it to calculate the outline of my tracks the way I need there’s not much point.

Playing with OSM data

I’m playing with OpenStreetMap data in PostGIS, drawing maps in QGIS. No serious cartography, mind you, just trying to get a feel for the data. I’m starting with Mike Migurski’s metro extracts, the .osm.bz2 file for San Francisco

Import that into PostGIS, which gives this schema which describes these map features.

osm2pgsql -d walks --style /usr/share/osm2pgsql/default.style san-francisco.osm.bz2

For the SF metro, there’s 8000 roads, 40,000 polygons, 31,000 points, and 62,000 lines. You can import all these tables directly from pgsql into QGIS and render them for a basic view. The lines contain the street grid; roads contains just the larger highways, etc.

QGIS makes it easy to explore the tables. When you add a new PostGIS layer and choose a table, you can then choose specific fields and sample their values. Exploring around you can find that “leisure=park” is an interesting subset of polygons, for instance.

Roads are terribly complicated, so to simplify I tried using Migurski’s High Road. It creates custom views with names like “planet_osm_line_z14” where just roads relevant at that zoom level are present. Also some fancy stuff to make drawing casings vs. road surfaces easier. z15plus is the big set of all roads (170,000); _big is 24000 roads and _small is the other 144,000 lines (footpaths and such). Unfortunately QGIS can’t use the High Road views; details in this issue I filed.

I was able to use the High Road code as a guide for categorizing road by size, though. The “highway” field is the key one. It’s a messy schema, there’s about 7 synonyms for “street”.

Here’s a map of the walks I’ve taken in my neighborhood, with streets and parks.

 

Scraping GPX files out of RunKeeper into Postgres and QGIS

I’ve been using RunKeeper to track my walking. I wanted to work with the 40+ GPS tracks they’ve logged for me and didn’t want to download them one at a time. Some quick notes on how to scrape them all out.

  1. Log into the website in your browser and go to your Activities page. It has a URL like http://runkeeper.com/user/USERNAME/activity/70000177
  2. Save that big HTML page to a file named activities.html
  3. Capture the IDs of all your activities from that page with a regexp like this:
    printMatches  ‘link=”/user/USERNAME/activity/([0-9]+)’< activities.html > ids
  4. You can now download a GPX for that ID with a URL like http://runkeeper.com/download/activity?activityId=70000177&downloadType=gpx. However, the download requires a URL, at least if your activities are private.
  5. Look in your browser for your JSESSIONID cookie. That’ll stand in for a login.
  6. Use wget with that cookie. Here’s my little shell script to get them all
cat ids | while read id; do
  wget --no-cookies \
       --header 'Cookie: JSESSIONID=C~2BF2D2156284732CE8D8BDA900000000' \
       -O $id.gpx \
       "http://runkeeper.com/download/activity?activityId="$id"&downloadType=gpx";
done

Set up a PostGIS database with all the data

  1. createdb walks
  2. psql -d walks -f postgis.sql
  3. psql -d walks -f spatial_ref_sys.sql
  4. psql -d walks -f postgis_comments.sql
  5. for f in *gpx; do echo $f; ogr2ogr -append -f “PostgreSQL” PG:dbname=walks $f; done

ogr2ogr will create a fancy schema for you that contains every field ever seen in a GPX file. For RunKeeper data, the salient things are:

  • tracks.wkb_geometry: one row per track, multiline string
  • track_points: one row per point with a point, elevation, timestamp, etc.

QGIS did a fine job rendering the tracks table for me. I also pulled in a raster OSM map for a base layer from http://wms.latlon.org/.

Here’s a quicky query to get the length of a track in miles. Need to understand the ST_Transform better, also join to something else to get proper data about each imported track.

select name, ST_Length(ST_Transform(wkb_geometry, 2163)) /1609 as miles from tracks order by name;

A quicky view to simplify the tracks a bit, plus a query that compares the length of the original and simplified views.

create or replace view simple as
select
 ogc_fid,
 ST_Simplify(wkb_geometry,0.00005) as track,
 name
from tracks;

select
  tracks.name,
  ST_Length(ST_Transform(simple.track, 2163)) /1609 as miles,
  ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple inner join tracks
on simple.name = tracks.name order by name;