A list of some location trackers from December 2025. Mostly sourced from ChatGPT. This is for passive trackers that record where I’ve been, not focussed GPS track recorders you turn on for a hike.
For years I’ve been recording my location and experimenting with various analyses of the data. It’s interesting knowing where I’ve been! I even built a product with my friend Brad to track and visualize. But I haven’t used it in years. Truthfully if I want to actually see where I’ve been before I use Google Timeline, as diminished as it is now.
Anyway I’m still tracking. I use Mendhak’s GPSLogger to record things on the phone. It’s only available via the F-Droid because the Google Play store has gotten increasingly hostile to things that run all the time and track location. (Even though all the commerical spyware persists, starting with Google’s own). The other hassle is I never got clean data export. I have it writing files to the Android filesystem and syncing via SyncThing and it works but is awkward. GPSLogger has other export options.
GnssLogger by Google is aimed at debugging location sensors. It looks very cool but is not what I need.
GPS Time Tracker aims at helping you make a logbook, like for business travel. It’s been around for years, 100K+ download, 4.5 rating. Looks promising. There’s a paid version for 10 EUR. The docs sound like it has some significant background operation issues. And while there’s some English localization it’s not complete and it’s pretty shaky. I gave this app a quick try and decided it was not for me.
GPS Timeline :Location History has screenshots that look a little like Google Maps timeline. It only has 500 installs and no ratings. It has ads that are a little intrusive and the UI is buggy. I didn’t see any data export option. Not for me.
I think Mendhak’s GPS Logger may still be the tool for me.
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.
I use Mendhak’s GPSLogger to track my position. It’s a great tool but a little low level, and in particular its files access is a bit confusing because the docs are written in terms of a basic Unix model but Android has virtualized and secured file storage so many times it is hard to find things. (I hate this about Android; it still lets you use files, but it’s very confusing and no longer a visible part of the consumer product.)
My issue now is I want to back up my settings, reinstall the app, then restore the settings. GPSLogger allows for that! It’s a feature called profiles. Basically you get it to write all your settings to a .properties file, then you can restore them later. The question is, where is that file written?
I found the file by mounting my Pixel 8 as a USB drive, then on Windows going to This PC\Pixel 8\Internal shared storage\Android\data\com.mendhak.gpslogger\files. (Actually I found it using Windows file search, which took several minutes). There’s a Default Profile.properties there. Also a temp.properties I explicitly created. You may have to tell GPSLogger to save the profile first.
I can’t find the properties files using the Files app on the Android device itself. Nor Solid Explorer. Presumably these are being hidden or sandboxed by the OS?
The properties file itself is a simple text file with lines like startonbootup=true in it.
This whole path was deleted when I uninstalled the app. (No surprise! Android wipes apps’ saved files in most cases.)
Once I reinstalled the app and saved a profile once the folder was back. Just dropping Default Profile.properties back in the folder didn’t seem to work; the app may not reread that file? I created a new nelson.properties (editing the file first, the profile name is in the properties file). That let me switch to a new Nelson profile with my preferences loaded. There are a variety of other ways documented in the FAQ to load a profile’s file.
Everything seems to work on reboot. GPSLogger starts with the new Nelson profile.
I have GPSLogger storing my GPS tracks to /storage/emulated/0/Documents/GPSLogger. I can see that in Solid Explorer by looking at Internal Storage > Documents > GPSLogger. Syncthing also sees that folder and is syncing it for me. When I reinstalled the app it could no longer write to files there (an error in Log View). I had to re-enable “write all files” permission (GPSLogger prompts you to do this if you change the folder it writes to).
I verified everything’s working after the reinstall, all the way to my syncthing server the data that archives my data.
I made another complex OSM edit, marking a road closed for construction. Details of the closure are on page 2 here. Nevada Street Bridge (OSM) is closed to cars until Nov 1 2024 or so.
As with all things OSM, how to actually do something this complex is not clear and there are many ways in the free-form schema.
First as a practical matter, serious mapping apps aren’t just relying on OSM for road information. They are pulling road closures from other sources. Google Maps has the closure and is routing around it. The fanciest OSM routing app I know, OsmAnd, does not (yet) know about the closure.
I chose to do the edit the aggressive way. I changed the way from highway=tertiary to highway=construction and construction=tertiary. Ordinarily this is the kind of thing you’d do for a new road being built. But I think it will have the effect I want, I just have to remember to go back and edit it again in November when the road is open. As a bonus I was able to tag it foot=yes which captures that you can still walk through the area, just not drive.
The other option was to just add a Conditional Restriction to the way, as seen here or here. A tag like motor_vehicle:conditional=no @ (2018 May 22-2018 Oct 7). I didn’t do this. One reason is this tag seems mostly useful for tagging permanent things with relative timestamps, like “road closed to cars 8am to 10am evey weekday”. I was also worried that most OSM users don’t process such a complex tag and will default to showing the road open. And finally that date range syntax I pulled as an example is really hinky. The ISO 8601 syntax would be 2018-05-22/2018-10-07 but near as I can tell OSM does not have an ironclad standard to use ISO 8601 for dates everywhere. I haven’t seen ISO 8601 slash syntax for time intervals in any of the docs.
End of the day I just want it to look right on the map. This is good enough.
Update: a day later OsmAnd routes around the closure, I think because it picked up my edit. Both Valhalla and OSRM on the OSM website still show a route through the closed road. I have no idea if they have updated data or not, but I’m guessing not. Update 2: it took most of a week but now the routing on the OSM website bypasses the closed bridge.
Yesterday Google Maps tried to get me killed, sending me on a route near Grass Valley, CA that had me driving through this flowing creek. OpenStreetMap based maps want me to go that way too.
I’m not the only one Google routes this way. And the ford claims victims. On March 1 2024 someone had to be rescued from this same creek coming from the other side. Back in 2012 too.
Here’s a link to Google Maps routing for the area. And openstreetmap.org’s website. Both show you going over Sharmiden Way which is a ford. During the rainy season the crossing at Wolf Creek is not safe. It’s never really a good route, even if the road is dry it’s still unpaved and awkward. You really would rather go south another half mile to Brewer Road. Which Google offers but only as an alternative.
Nothing in Google’s data seems to indicate they are aware it’s a ford, not a normal road.
Tagging fords in OpenStreetMap
I can’t fix Google. But I can edit OpenStreetMap! Here’s the area in question; the ford is where Sharmiden Way intersects Brewer Road. When I started on this there was no indication the road was unusual at all. So I went and added a notation of the ford. True to open schema form, OSM has several ways to tag fords.
The simple way is to add a single node on the way and tag it ford=yes. I made that edit a couple of weeks ago. The result in the OSM default web map is a tiny blue icon indicating the ford. Not great but at least I can verify the data is on the map.
I made a new edit today, the second fancier way. Which is to create a whole separate way for the ford and tag the whole way with ford=yes. Actually the iD editor wanted to put ford=ford in there but I overrode it because from what I can see ford=yes is more common.
I left both node and way ford annotations in place. Now OpenStreetMap knows about the ford. Will software use that to avoid danger?
OSM routing through fords
Neither of the routing algorithms openstreetmap.org’s website seem to avoid fords. Both Valhalla and OSRM on happily send cars plunging through the swift-flowing creek.
The Android app OsmAnd does have an option (off by default) to avoid fords in routes. And it successfully generates the safer route.
OsmAnd is powerful but it’s really not a user-friendly app. Finding the option to turn off routing through fords it’s like four menu items deep. The map download process is slow and awkward. And the Google Play version of the app wants you to pay for updated maps, otherwise the data is weeks old (which makes testing awkward). The trick for that is to get the F-Droid version which has most of the Pro options unlocked at no cost. Even then you still have to find the extra “Updates” tab to get fresh data, it’s not in the ordinary downloads.
Now I’m curious if any maps avoid this ford. Google Maps can’t, it doesn’t even know the ford is there. OSM based apps now know but only if they’re using fresh data.
I tried Scout Maps, the only OSM app I could find for AAOS, but it still routes me through the ford. They say they use OSM data but there’s no way for me to see how fresh the data is. The app has a way to tell it to avoid unpaved roads but no explicit way to avoid fords.
I got a nice personal message on Mastodon about GraphHopper, a routing service. The default route uses the ford but at least shows a warning about it. And you can customize its algorithm to avoid the ford.
There’s a classic style of visualization on the Web; “dots on a map”. You take a basic Google map or whatever and draw dots on top of it to indicate things: locations of stores, tourist highlights, demographic data, whatever.
Sniffies is a gay hookup app in the vein of Grindr or Tinder. It has a nice dots on a map Web UI so you can see people around you. Only instead of dots they’re little bubbles with user photos. This being a gay app, what that means is lots and lots of photos of intimate anatomy. Dicks on a map.
Image below is NSFW.
A MapBox map with many penises in location circles
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.
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.
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.
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.
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”.
This is what you get in QGIS if you use its hillshader and then zoom in finer than the resolution of the DEM data. May need to view image full size to get the effect.
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.
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.
Summary: after 9 months, the GPS data being logged by GPSLogger on Android looks good to me. At least good enough for Wanderings’ location tracking and heatmap.
One casualty of my switch from iPhone to Android is my own Wanderings app, a lightweight GPS tracker that Brad and I worked on together. There’s an iPhone app that tracks your movements and records data and a webapp that displays the data. But we don’t have an Android version of our tracker and I’ve been unmotivated to learn enough Android to write one.
I have been running Mendahk’s excellent GPSLogger though and it is faithfully recording my location every day to GeoJSON and CSV files in Google Drive. I finally got around to collecting all that data and visualizing it with our web app. Qualitatively it looks the same as the data collected a year ago by the Wanderings tracker. That’s good! See screenshots below.
I haven’t done a deep quantitative comparison. But GPSLogger recorded 218,451 points over 284 days, of which 90,877 points were more than one minute apart from each other (a cutoff we use). By comparison our own tracker only stored 6248 locations for me over 574 days. That’s 319 points a day compared to 11! GPSLogger calmed down a whole lot though starting in September, down to about 70 points a day. I suspect that’s when I disabled passive location tracking, resulting in many fewer points logged.
Still GPSLogger is recording 7x as many points as Wanderings. The extra points are harmless to the visualization output but they do incur some storage and processing overhead. The Wanderings tracker is using the iOS Significant Location Change service and only seems to record points when you’re really moving. GPSLogger is configurable in recording granularity. I have it being somewhat aggressive: GPS/GNSS locations, network locations, and a 60 second logging interval with a 10 meter distance filter to log a new point.
I went ahead and looked at distances between points in the GPSLogger output using geopy’s calculation. A whole lot of pairs of points are less than 20 meters apart. I don’t really know what’s correct here, since you do want to capture data with fidelity when the subject is moving. Probably overthinking it. Here’s a quick and dirty histogram of distances for all pairs less than 100 meters apart.
And here’s the promised gallery of app screenshots. Two similar time periods, one year apart. The older is the iPhone tracker and the newer is GPSLogger on Android. They really do look similar.
I’ve been running Mendhak’s GPS Logger for a few weeks now on Android. It’s good! Some details on precisely what it’s logging. I’m using this as notes for building my own GPS tracker for Wanderings. GPS Logger is good but I think it’s better to have a custom one for us.
Bottom line: the CSV format is most complete, GeoJSON has most of what you’d want in a GIS-friendly format. It logs points once a minute by itself in a mix of network and GPS modes. When a location tracking app like Google Maps is also running, GPS logger will logs points as often as once a second. Now the details...
Some of this is configuration dependent; I have it set to Log all 3 sources: GPS/GNSS, network (cell/wifi), and also passive (other apps). Logging once a minute, GPS not turned on between fixes, no distance filter. Accuracy filter dialed down to 200 meters. 60 seconds to get an accurate fix, 120 second timeout on the GPS fix. I’m logging simultaneously to GPX 1.0, CSV, and GeoJSON.
Most of this data comes from 2017-05-26, when I started in Hickory, NC and flew home to San Francisco, CA. Most of these observations are based on the CSV file which the author has said is the most comprehensive.
The data files are one-per-day. They seem to contain data from local midnight to local midnight. There are sometimes gaps of several hours, I believe related to low power / sleep modes in the phone. Particularly common in the middle of the night when I’m not moving.
On 2017-05-26 the CSV file has 6975 data points.
When I’m sitting idle in my hotel most of the fixes are of type “network”. There’s typically one entry per minute (with frequently two duplicated rows). The CSV file for those populates time, lat, lon, elevation, accuracy (typically around 20), and battery. Occasionally a fix of type “gps” also shows up; those have an accuracy of about 10. They also add bearing and speed, although when not moving those are presumably nonsense. Also HDOP VDOP PDOP and GeoidHeight, GPS-specific measurements. There’s a field for ‘satellites’ but it always seems to be 0.
Once I start driving around 14:50Z I also turned on Google Maps for routing. At that point all the fixes switch to GPS and I’m getting one a second. Accuracy is around 3 and satellites still 0; no HDOP/VDOP etc though. Plausible bearing and speed data. I’m guessing these are points GPS Logger got passively? This pattern is repeated a second time on a longer drive. Google Maps for navigation again then although I’d made an effort to turn the screen off for part of the drive.
During my flight from CLT to SFO I had the phone in airplane mode and in various pockets, etc with varying ability to see the sky. GPS Logger seems to be trying to record 1 point a minute. When it succeeds there’s two duplcate rows in the CSV, one with HDOP/VDOP data and one without. Altitude, speed, and bearing all look plausible. I mostly have no data from when I had the phone in my pants’ pocket; shirt pocket is better for obvious reasons.
Last bit of the day was me in an Uber, no Google Maps running. Odd mix of GPS and Network fixes about once a minute. It’s possible the Uber app was doing location tracking in the background, I’m not sure.
The 2019-07-26 GeoJSON file also has 6975 data samples in it. Every point has lat, lon, time, time_long, provider, accuracy. Almost every point has altitude (6759), 5032 have speed, 4094 have bearing.
The GPX 1.0 file also has 6975 data samples in it. lat, lon, elevation, time, and provider for almost all points. course and speed for GPS points also. There is no accuracy logged.
A special note on elevation: these seem to be WGS84 altitudes, before the geoid correction. (I have Use MSL instead turned off in the app.) That’s putting me underwater frequently in San Francisco, even the points from network sources. Need to think more carefully about geoid correction if I want to use this data.
I’ve made the switch from iOS to Android. One thing that means is I need a new GPS tracker; my own Wanderings app is iOS only. I may end up writing an Android custom app myself to do that.
For now I’m using the excellent GPS Logger app. It’s a very flexible passive location tracker, open source, lots of control over exactly what kind of data to log and where to upload it to.
It has three sources of location updates:
GPS/GNSS locations. Honest to goodness satellite fixes
Network locations. Info based on wifi and cell tower fixes
Passive locations. Any time any other app gets a location, GPS Logger gets a copy
I currently have #2 only turned on and it seems very low battery impact, certainly OK to leave on for 24 hours. Once a minute it wakes up, asks the phone where it is, records the data into an internal log file, then goes to sleep. The location data seems pretty inaccurate though, I need to look closer.
I tried #1 for awhile and it seems higher power impact; not sure you can leave it running for 24 hours. (Update: it’s not nearly as bad as I first thought, and might be fine for daily use. Even once a minute.) Data is quite accurate but demanding. It wakes up the GPS chip, waits for 1-2 minutes for a good fix, then records the location. You can also tell it to leave the GPS chip on always, but there’s a warning about “dramatically decrease the battery life”.
#3 seems like a freebie, of course you should use it. I only have it turned off because I’m trying to keep it simple so I understand what GPS Logger is doing itself.
They also have abilities to filter points based on reported accuracy of the fix, and how far you moved. And there’s a way to tell it only to log if the accelerometer detects the phone is moving.
What I haven’t found in GPS Logger is anything like the “significant location changes” API that Wanderings uses in iOS. Nor anything like geofences / regions. Those may be in the Android API and just not in this app.
Update: after a few days playing around with GPS Logger I have some extra notes.
I’ve been running the GPS Logger app on Android in full logging mode for a few days now and its impact on battery life is neglible. My whole phone only uses ~40-50% of its battery in 24 hours. 0.1% of that is attributed to GPS Logger itself. 42% is the wifi radio, 25% if the screen, 10% is the OS.
GPS Logger is currently logging my position once a minute. I’ve told it to use both GPS and “network locations” (wifi/cell). It seems to request both types of position at once and almost always the network location answers first, so it never logs the GPS. I’ve run it in GPS-only mode too to get real GPS fixes, those often take 20+ seconds and don’t work great indoors.
The most problematic thing is that GPS Logger doesn’t log points at all for hours. AFAICT this is a significant problem in Android phones in general, that background apps often don’t run when the phone is in “doze mode”. It mostly happens in the middle of the night where I’m definitely not using the phone so it might be the “right thing” but it’s a problem. I’ve read various hacks and workarounds, see the GPS Logger FAQ. GPS Logger has a gimmick where it constantly has a notification on screen to try to stay more lively.
Funny thing; some apps I don’t even actually use are consuming more battery than GPS Logger. Like Maps.Me was using 2% a day until I went in and told it to be “very low power”; I haven’t even launched it! Google Fi also uses 1% even though I’m not using it.
A friend of mine is an anthropologist expert on Papua New Guinea, particularly Enga Province. There are precious few good maps of PNG (famously) so he’s asked me if I could help prepare a schematic map of the region he can use in a publication. If it goes well maybe we can submit the map to Wikipedia or something too.
For inspiration I pulled a bunch of sample maps from Bing / Google / Openstreetmap, also from the Rumsey archive and various online sources. I particularly liked this map (from this paper) and the SIL map. Openstreetmap’s default map style isn’t bad, either, and I’m encouraged by how much data OSM has. (I don’t need detailed roads, just a single image at large scale.)
It’s interesting how some of the custom maps emphasize roads, others emphasize rivers. Really terrain is a pretty key element of understanding the area too, it’s quite rugged, but most of the maps I see are constrained by print restrictions to not including terrain.
I’m also starting to read up on Wikipedia’s guidance for maps. WikiProject Maps is a good place to start. I really like their exemplar of The Big Island of Hawai’i; the combination of coloured elevation contours and subtle hill shading is great as a base for the map symbols. They also have an SVG template for icons and such. A lot of these principles only work in color though, and I think for print I have to go greyscale.
As for implementing this, my plan is to start with Natural Earth and OSM data and rough something up in QGIS. And then start working in earnest with a tool to extract the data I need and export it to SVG format. Mapnik maybe? Then use Inkscape to further style and deliver the SVG, also allow non-map experts to add text annotations. Or maybe I can lean on QGIS more than that and not write custom code to emit the SVG I need. Looking forward to learning more.
A group over at Facebook has released a valuable new dataset, High Resolution Population Density Maps. They used machine learning to look at aerial imagery and figure out where people live, then put dots on a map (one per arcsecond) with estimated density. Their post goes into detail; the data now is most of Africa with the whole world planned. There’s not a great browser for the data but the files are easy to work with and smaller than you’d think; a few megabytes per country.
I took a quick pass at the Liberia data in QGIS, here it is plotted by quantiles on top of Stamen Toner Light:
It’s immediately apparent that the density data is banded. Each red dot in Monrovia, for instance, has the (exact) value 23.255445274781373. Half the dots have no value, even in the middle of the city, maybe because no single building was reliably detected in them? The orange dots north of there are about 9.3. Some small villages out in the hinterlands show very high densities, like 45. I don’t know if that’s at all like reality or rather an artifact of detecting relatively few buildings in a big rural area.
By contrast Johannesburg has much more variation in densities. Maybe South Africa has better data on population-by-region than other places
Nigeria’s data is somewhere inbetween. Lagos has big regions of uniform density but there is at least some variation. I can’t figure out what the building detection did in the rural areas. Their system did correctly figure out there are people in this general area, but the dots and the buildings don’t particularly line up.
I’m no expert in this kind of data and have no idea what the state of the art is. But this looks to me like two separate datasets mushed together. One is new and fine grained, a binary yes/no building per arcsecond based on image analysis. And then there’s some larger granularity numerical “X people per building” that they’ve taken from some other data source, maybe government census data. The combined data is them just applying that number X to the binary thing about whether there’s a building or not.
It’s not bad! But I had initially thought they were doing something more subtle, where they were estimating building size or height or density. If I’d read their description more closely I would have already realized they were not doing that:
we redistributed all the census counts equally over all the buildings found within that census area. This method assumes equal population distribution per building within a census area, which we felt was the least error-prone method of obtaining population densities since it doesn’t make any assumptions on the number of people per building and constrains systematic errors to within one census area.
For an alternate take at the data, @Mikel took a shot at a slippy map using MapBox, you can see the result here. I had trouble getting it to load new points past the initial view. But see the screenshot below
We have a special election for California State Senate in District 1 this year. Judging by past elections this district is roughly 65% Republican. I was confused because California’s National Congressional District 1 looks like a very similar part of California, the northeastern rural part. But it was only 55% Republican last year. Why the big difference?
So I made a map of the difference between the two districts. Turns out the Congressional district includes a big part of the northern central valley including Red Bluff, Chico, and Oroville (outlined in blue). (Also a tiny bit of rural area north of Roseville.) The State Senate district instead includes a chunk of the middle Sierra including Truckee and Placerville. I don’t have demographic data in front of me but it seems plausible that explains the political difference. Static map below, there’s also a slippy map online.
Details: I used 2017 data from the US census, The files are cb_2017_06_sldu_500k and cb_2017_us_cd115_500k. I then did some QGIS munging (finally, easy basemaps!) to calculate the simplified symmetric difference and display it reasonably.
I finally closed the loop on a long-standing problem we have had with our Wanderings location tracker. We wrote our code to be very low impact; it uses the Significant Location Changes API on iOS to track your movements in a very passive way. But our app was causing the phone to use as much as 100 MBytes/day when running in the background! All that bandwidth was accounted to “Time & Location” in iOS itself, not our app.
Much sleuthing later we narrowed the problem down to Mapbox Metrics, their telemetry service. You can see some discussion in this bug report, but the behavior is expected, not a bug. And somewhat unique to our app. If we turn off telemetry our usage goes down to < 1MB / day of data.
By default telemetry is turned on if you use Mapbox native in your app. And it listens to location updates your app gets. If your app gets a notification the person has moved, Mapbox then requests fine grained location updates for a short period of time. (5 meter movements for 5 minutes, I believe.)
There’s nothing nefarious or dumb here. The location telemetry is a disclosed part of the product and the code is open source. They have appropriate privacy protections. And it’s a reasonable form of telemetry for most apps. I imagine most Mapbox apps have the map front and center as part of the UI with location tracking already enabled, so Mapbox’s telemetry requests don’t really generate any more traffic. Unfortunately our app is just unusual in wanting low impact background updates only, not a good match for the telemetry behavior. Fortunately our users can turn off the telemetry tracking if they want. (In fact, Mapbox requires that apps provide a telemetry opt-out option for users.)
The other confusing piece of this is why does location tracking use so much network bandwidth, and why is it attributed to iOS itself and not our app? Only Apple really knows, but I have some guesses. Phones almost never use an honest GPS signal to track location; mostly location is tracked by reference to nearby Wifi and cellular signals. My guess is every time the phone wants to know its position the iOS location daemon itself makes a TCP/IP request to some Apple server to do a lookup. (I’ve definitely noticed that my location tracking goes way worse when I have cellular data turned off, say when traveling in Europe.) That data usage is significant if you are tracking location in a fine-grained way. And since the request comes from iOS and not the app, the bandwidth is accounted to iOS itself.
While I’m guessing, I think in practice “significant location change” means “moved into range of a new cell tower”. My guess is those location updates come “for free” because the cellular chip already has to do a bunch of work for tower handoffs. Based on observation, moving in range of a new Wifi network is not enough to trigger the location update.
A lot of digital maps use zip codes as a binning feature. Election maps, property value maps, pollution maps. But while zip codes are convenient and familiar there’s a much better set of polygons for mapping most US data: census tracts. Zip codes are pretty unusual polygons(*), drawn mostly to make the process of mail sorting and delivery simpler. They are quite arbitrary. Census tracts are lovingly and carefully drawn to respect demographic and political reality.
I have a great example of the difference: River Oaks in Houston, one of the wealthiest neighborhoods in America. It’s the place where Saudi princes buy a 10,000 square foot house and glass in the backyard so they have air conditioning. Also plenty of local Houston money, mostly old money.
But you’d never know it looking at zip code averages. Because River Oaks shares 77019 with a bunch of people who live east of Shepherd, in a significantly denser, less wealthy, more diverse neighborhood. It also includes big chunks of the Fourth Ward which used to be quite a poor neighborhood and was recently redeveloped. By contrast River Oaks is almost perfectly described by census tracts 4112 and 4114. (Not exactly; the chunk in the SW of 4114 is not technically River Oaks, nor is it in 77019, but demographically it’s quite similar to the rest of 4114.)
Zip code 77019River OaksCensus Tracts
Census tracts are part of a hierarchy of census polygons. Census tracts aim to have about 4000 people in them, (zip codes average 8000 people, but vary greatly). Block groups are smaller and have ~1500 people each. Census blocks are the smallest division, about 40 blocks per group, but unlike census tracts they are highly variable (in terms of statistical demographics). There are 11M census blocks in the US, although nearly half of them are uninhabited.
Census tracts are frequently named by 4 digit numbers like 4112 or 4114, with a county name or something else to disambiguate them. But some tracts have numbers with decimals or other complicating factors, like 32 or 204.01. (I believe canonically census tracts are named with 6 digit numbers, with the decimal and leading zeros frequently omitted).
FIPS codes are the larger naming scheme; the full name of 4112 is sometimes given as 48201411200. 48 is Texas, 201 is Harris County, 4112 the census tract, and the 00 is the block group. Census blocks get their own 4 digit number at the end, making for a full 15 digit code to name the most precise polygon.
(*) technically speaking zip codes are actually just lists of points. The polygons are properly called zip code tabulation areas and there are some important differences.
Interesting study summarized over at The Economist. The researchers tracked the movements of 40,000 people as they went about their daily lives. They found the number of places that people go to regularly is about 25. That set of 25 places changes, but when someone adds a new place they tend to stop going to the old place. The result is kind of like a Dunbar’s number but for places, not relationships.
To be honest I didn’t get a lot more out of the paper than the Economist article. The statistical methods are unfamiliar to me and I’m too lazy to figure them out. But some details:
They define a “place” as anywhere someone dwells more than 10 minutes. These are characterized as “places offering commercial activities, metro stations, classrooms and other areas within the University campus”
People discover new places all the time. The fit is exponential, roughly
locations = days ^ 0.7 over a span of ~1000 days.
The probability a new place becomes part of the permanent set is somewhere between 7% and 20%. The Lifelog dataset (their largest) yields 7%; the others are 15-20%.
There’s four separate datasets. Sony Lifelog is the big one; that’s like Google Timeline combined with a fitness tracker. But also several academic datasets. One of those, the Reality Mining Dataset from the MIT Media Lab is publicly available and covers 94 people.
Interesting research. I wonder if it’s really true? It seems plausible enough and matches my personal experience. Particularly since I split time between two cities; I go to fewer places in San Francisco regularly now that I am half time in Grass Valley.
My sister now lives on a sailboat and is traveling the world. Good for her! I’d like to keep track of her boat, follow the adventure. This turns out to be totally doable thanks to the fact the boat has an AIS transceiver. Here’s some notes on tracking location with it.
The two best free sites for AIS tracking I’ve found are MarineTraffic.com and VesselFinder.com. There are also many more sites that do similar tracking with varying user interfaces and premium subscriptions for extra features like historical data. But the big difference with these sites is their source of AIS data.
AIS tracking mostly works by relying on a network of receivers installed on the shoreline. Receivers typically have a 15-20 mile range. MarineTraffic runs its own network of receivers. They have 3488 receivers, you can make a map of them. Many other sites, including VesselFinder, cooperate via AISHub. That’s a hacker-friendly project to try to get many AIS sites to share data. AISHub coverage is spotty, they currently have 543 receivers. But sometimes they have one in a spot MarineTraffic doesn’t. Here’s some other sources of AIS data, including historical archives.
There are also satellite AIS receivers in orbit so you can track a ship world-wide. Apparently AIS wasn’t designed for this but with some careful radio engineering the signals can be detected from space. I don’t think there are any free satellite AIS sites, but MarineTraffic sells tracking for a single ship for $16.50 / month using ORBCOMM satellites. A lot of the other products I saw were $1000s aimed at commercial customers.
I think a receiver that relays to the Internet can be pretty cheap. Here’s some discussion about doing it with a simple SDR and a Raspberry Pi. But for a proper installation you probably want a real antenna and a robust outdoor deployment and a cellular uplink, so I imagine a robust receiver is a few hundred bucks. MarineTraffic gives receivers away to people who can expand the network, more details in their FAQ.
AIS transmitters come in various flavors. My sister’s boat has a Class B transceiver, expensive commercial operations use something fancier. It works at around 162MHz transmitting 38400kbps at 2W. Data is in NMEA format and includes a position update (from GPS) every 30 seconds. The devices are full transceivers, they receive positions from other ships too and can be interrogated for more detailed info. Messages include a unique identifier called an MMSI. Ships also broadcast extra data like their name, ship type, etc every 6 minutes. It’s all pretty similar to ADS-B used in aviation but seems rather further along in actual deployment.
Over on Metafilter I learned about the project Queering the Map. I like it! Simple project to let people share their LGBT experiences on a map. I like the anonymous confessional aspect of it, also the visibility and power of LGBT people sharing our experiences.
I liked it so much I made my own visualization: Queering the Heatmap. I took a static snapshot of their textual data and put it into MapBox GL JS. Mostly I wanted a heatmap of comment density. Also was curious if it’d be faster than the Google Maps site, it definitely is. Just took a couple of hours, thanks in large part to being able to crib map code from my Wanderings project.
Doubt I’ll do anything more with it, at least without permission and cooperation from the folks in Montreal who run Queering the Map. I think without the “add point to the map” feature it’s not really that exciting, and of course I shouldn’t do that without permission from them. Particularly since they had to deal with a troll attack recently.
Screenshot below. Not sure the heatmap setup is quite right, but I got tired of tinkering with gradients.
Edit: this blog post is so self-deprecating! Lol. I like this little project, I’m proud of being able to make something pretty like this in a couple of hours. Wouldn’t mind doing this as a more real thing if the folks running the project like it.
Great location in the middle of a fun central neighborhood. The front door is on the east side of the building, on Victoria St itself. But that map pin there is in the middle of the building, the centroid of the rectangle. And that means a lot of map software guesses the address is just a bit closer to the west side of the building, to that little Hayden Ln. Which is a back alley you can’t really drive in and isn’t accessible from the apartment.
This caused real problems with Uber. Their routing software would sometimes try to send the driver up to the back alley.Drivers are smart enough not to do that, but following the purple line put them on Liverpool St where they can’t turn left on to Victoria St to drive to the actual door. This detail mattered because one of us was injured and couldn’t walk the half block down to Liverpool St. Also the routing was unstable; sometimes it directed drivers to the east side on Victoria St and then would flip mid-drive to the west side on Hayden Ln. Which changes the whole route by half a kilometer because Victoria St is one way.
We have the official address point data from the Australian government on OpenAddresses. They geocode the address as 151.2212399,-33.8779683 which is just a hair further southwest than the Google Maps pin. That’s the official correct location for the address but it does not describe the ground truth. Bing Maps has more or less the same wrong point as Google, so does Apple. OpenStreetMap doesn’t have the street number at all and guesses the wrong segment of the road.
The underlying problem here is the database has the polygon for the building but not the exact point of the front door. So it guesses a point by filling in the centroid of the polygon. Which is kinda close but not close enough. A better heuristic may be “center of the polyline that faces the matching street”. That’s also going to be wrong sometimes, but less often.
One extra wrinkle: our proper address was “3/239 Victoria St Darlinghurst”. It’s not enough to say Sydney, you have to name the actual suburb Darlinghurst, because there are multiple Victoria Streets. And the 3/ is an essential part of the address, naming the apartment unit number. Various official forms won’t just accept “239 Victoria St”.
PS: Gelato Messina is excellent.
Update: a friend at Mapbox tells me they do something similar to my heuristic. It’s implemented in this library and is in process to be added to their geocoder. He describes the algorithm as “drawing a bisecting line from the address point to the closest point on the street line”. I imagine the details are more complicated.
Update 2: a second example, 2324 Sacramento St SF, CA. The map pin is in the middle of the building which caused our Deaf Uber driver to go to the “closest” point, that stupid alley on Clay St. There’s a lovely driveway and drop-off location right at the street frontage on Sacramento that we could not get the driver to go to, between communication difficulties and map failures.
At Kiwi Foo I met someone who was interested in the Hawaiian Homelands, so I revised the map I made and got it working again. Refreshed the data too, the state published a new file from the 2015 census that includes population information. The new slippy map is here. I also made a rough GeoJSON view using geojson.io; just the converted state data, no ahupuaʻa or interpretive mapping.
From a technical point of view the main thing I had to do was convert the map from using Mapzen (RIP) to vanilla Leaflet. Not too hard since Mapzen’s Javascript was based on Leaflet, but I’m lacking a good replacement for their geocoder search. I replaced their map tiles with Carto’s Positron. Here’s a good list of free map tiles that I found that on. I probably should have just done the whole thing again in Mapbox GL JS but that was more work than just porting from Mapzen to Leaflet. Also Mapbox isn’t a free service.
I didn’t do more on this project before because I don’t understand the history and importance of the Hawaiian Homelands enough to really do it right. But the guy I met has a lot more knowledge and knows some folks, we may work together to do more. A good static map for Wikipedia seems valuable, something simple like the state’s preview. I’d love to get more specific data about every individual parcel, there’s only 75 and they must have interesting histories. Maybe turn that research into a magazine article or something.
Working on adding data import to my Wanderings project so I can bring in data from other trackers. I have 6 years of data from OpenPaths. And when I imported it the first time I got so much joy out of seeing it again. Particularly trips to India and France.
Our Wanderings project uploads location fixes with the iOS significant location changes APIs. It includes an accuracy number, distance in meters, and occasionally we get points with accuracies > 1000m. We’re about to stop displaying those, but before I do here’s what the data looks like:
That shows most points have an accuracy of 10m, a significant number have an accuracy of 65m, and a few have 1414m. This histogram tool is misleading, there are also 15 points with an accuracy > 1414m. (Shout out to 7094 meters; you did your best, little iPhone).
If I had to guess, I’d say 1414m means “location from a single cell tower” and 65m means “location from a single wifi access point”. But who knows. It’s possible to ask the iPhone to give you more accurate fixes, we’re deliberately only using the most low power location monitoring to conserve battery life.
My friend Brad and I launched Wanderings, a simple location tracker app for iPhone and Web. Put it on your phone and forget about it, come back a few weeks later to have a nice heatmap of where you’ve been. It was inspired by the late lamented OpenPaths. See also Google Timeline, which is much fancier but doesn’t have a heatmap.
I was inspired to start working on this while traveling in Berlin. I just want to know where I’ve been, you know? I don’t know anything about building iPhone apps but fortunately Brad does.
The best part of the app is that we went serverless; we don’t have our own database or server processing location points anywhere. The iPhone app uploads directly to iCloud. Javascript in the web page downloads it directly and renders it. That’s good for privacy and also simplicity. I seem to be building all my web apps this way these days; Logs of Lag, Wind History, etc all work without significant server components. Sure is easy to scale and maintain.
Garrett Dash Nelson has a lovely visualization of snowfall for 2017-2018; take a look! His code is very simple. A Python script to download data from NOAA, then some bits of shell scripts using GDAL to reproject, hill shade, and convert to an animated GIF.
I wanted to see what this treatment would look like over years so I did my own little thing based on his. Here’s the image processing script I used
#!/bin/bash
set -eux
for y in 2014 2015 2016 2017 2018; do
d=$[y-1]-$y
gdalwarp -t_srs "EPSG:5069" -srcnodata "-99999" sfav2*to_$y*.tif $d-warped.tif
gdaldem hillshade -z 1500 $d-warped.tif $d-hillshade.tif
gdal_translate -of JPEG $d-hillshade.tif $d-hillshade.jpg
done
And the images below. Starting at 2013-2014, and the final image is just a partial year of 2017-today. It’s not a great result TBH; the years end up looking pretty much the same and not that different from an altitude graph. In California you can’t see the low snowfall years of 2014-2015 and 2015-2016 vs the high snowfall 2016-2017, for instance.
Strava just published a new map of all their data. 3 trillion GPS points turned into a heatmap. It’s lovely.
They wrote a fantastic writeup of how they made the map. All custom software. It’s not really a “heat map” in the sense I use the term, in that it lacks heat diffusion that leads to blobbiness of a true heat map. It’s more of a spatial histogram. That’s just a quibble, but it helps me keep this visualization straight from the new Mapbox JS GL heatmaps I’m playing with.
The smartest thing they do is adaptive normalization of the colormap to spatially local data. They describe it in detail with the CDFs they calculate. Basically bright yellow indicates the highest number for a local region near where you’re looking now, not an absolute number for the highest value in the whole world. This allows seldom-visited areas to still have compelling and readable visualizations. You can see this in effect if you zoom in to Alcatraz which has relatively few visits; the brightness changes radically from z=15 to z=16. A trick worth stealing.
I was also struck at how all the tracks look nicely snapped to roads. Mobile phone locations are never that accurate. And they deliberately fuzz all points by 2 meters, why are the roads so sharply defined? I think they simply have enough points that the average that comes through visually really is the actual road. Neat! You can see this in a hyper-zoom on the Golden Gate bridge where you can see faint traces of tracks off the bridge, but the main bridge path is highlighted. Note also the little bump, that’s where you have to walk about 2m to the outside to avoid the tower. (I believe the two tone-line is because this is walking data, pedestrians tend to walk the east side.)
I mentioned wanting a heatmap for some geographic data. Leaflet has a variety of heatmap plugins, I spent a couple of hours looking at them.
First, a word about heatmaps. A true heatmap has a feature where if you keep adding points (“heat”) to a spot, that heat diffuses and spreads out. In theory you could cover the whole world in hot red just adding to a single lat/lon because the heat diffuses (unless you have cooling/decay enabled). I want this feature. Calculating diffusion like this is complicated and slow. So most “heatmaps” cheat and instead of running a diffusion algorithm just draw blurry transparent dots. When they overlap it looks a lot like a heatmap, but you never get the full diffusion. It’s a reasonable compromise for a lot of applications (and way faster, particularly since it’s GPU-friendly) but it’s a compromise I’m hoping to avoid. See also this technical discussion.
Another key thing is how map zooming is handled. The heat blobs are really rendered in terms of pixels, not meters or geographic degrees, so the heatmap picture needs to be re-rendered at every zoom level. Some of the libraries look like they just render one image and raster scale it to match the zoom. The behavior I want is visible in this demo: notice how the blobs get more detailed when you zoom in.
Anyway, here’s my quick review of the 7 plugins:
Leaflet.heat; first one I’ve used. Canvas based, seems to work for 20,000 points no problem. Not a true heatmap, just fuzzy circles, but it looks good. Last update a year ago.
heatmap.js: canvas based, I think a true heatmap. Demo doesn’t recalculate on zoom the way I want and I don’t think there’s code for doing it. The library is mostly used for rendering user attention on web pages.
webgl-heatmap-leaflet. I gotta think WebGL is a good idea. New code, mostly 3 months old. Unfortunately it doesn’t seem to have the zooming behavior I want. There’s some scaling code (units and size option) but that seems to be about projecting circles of a consistent size at different latitudes.
Leaflet-solr-heatmap, see examples here. It’s pretty impressive being able to handle 10M points but the grid display isn’t what I’m looking for.
leaflet-div-heatmap is clever for using CSS and divs. No live demo I could find though, and no commits in 4 years, so I stopped looking.
MaskCanvas: not a heatmap, more of a “reveal the map” display. It’s neat though! Last real update was 2 years ago.
HeatCanvas: true heatmap, a bit too oriented towards static images. Not sure if it works well in zooming. Last real update was 4 years ago, I didn’t look further.
In summary: Leaflet.heat is the one I want. It’s the only library that recalculates on zoom. The downside is it’s not a true heatmap. I think that actually matters for my application (I expect a lot of dwell time in one place) but it’s a compromise I can accept.
I want a passive location tracker on my phone, something to tell me where I’ve been over the span of years. Google Timeline + Android does this pretty nicely and this blog also has previous notes on Fog of War and other gamified apps. I was using OpenPaths on my iPhone to do something similar, but it was abandoned. The backing server is already gone and the app will die with iOS 11.
So what to do? A friend suggested OwnTracks, an iOS tracker. This isn’t civilian software; there’s no public service. The docs are all about running your own custom server to collect your location data. But the iOS tracker is capable. In particular you can choose battery vs. accuracy. You can either record your position every N seconds / every M meters, which takes about 10% of your battery an hour. Or you can use a more passive “significant movement” mode that is less sensitive but uses very little battery, maybe 1% an hour. I think that’s what OpenPaths did; I ran it for years without a problem. (There’s also a newer iOS API for “Visits” that also looks useful).
OwnTracks publishes data via MQTT, a message queue protocol designed for Internet of Things apps. It seems awfully complicated and a bit fusty, but if they’ve thought through reliable, low power connections for limited devices I’m glad to use it. The OwnTracks docs have some info on running your own MQTT server but that seemed complicated, so I’ve started with CloudMQTT which has a nice free level.
I created a CloudMQTT account and then just plugged in the Instance Info username/password into OwnTracks and set it to logging. CloudMQTT has a “Websocket UI” that shows you the message stream to verify the plumbing is working. OwnTracks reports look like this:
So that all works. Now what about capturing that data for myself? After some false starts I ended up at paho-mqtt, a Python client. The example client on that page more or less works, except you have to modify the on_connect() function to take a fourth flags parameter. (That’s a hint this code is musty.) The example connects to some public MQTT endpoint with a bunch of events flying by so you know it worked. Eventually one sent non-UTF8 and broke the Python code, but at least it was working.
Last step was to reconfigure the sample client to connect to my CloudMQTT instance. To get that working I had to create a new user and set it up with the ACL controls. (Wildcard access, read/write). For some reason the main user/login didn’t work; maybe because it was in use by OwnTracks? I also had to call client.subscribe() to get messages on my specific OwnTracks topic; not sure if that is supposed to be necessary.
Cloud MQTT also has support for forwarding events to Amazon Kinesis. I set this up hoping it was an easy way to get at the data but it just adds complexity and another system for me right now. There’s probably some way to feed the data into a database with AWS plumbing that might be nice. And it’ll scale!
Things to learn more about with MQTT:
Is MQTT a living tech, or is it abandoned?
CloudMQTT user management
paho.mqtt: naked TCP vs TLS vs Websockets
MQTT topics and subscriptions
Is Amazon Kinesis interesting for my application? Would be nice to have less code + servers to manage
Spoiler: this is a summary of a failed experiment.
There’s a wonkish new measure of gerrymandering that’s influencing the courts called the efficiency gap. It is a measure of partisan bias of a districting plan, trying to quantify “wasted votes”. It’s not too complicated a measure. Suppose a single district election goes 53 voters for candidate D and 47 for candidate R. Then 2 of those D votes were wasted, because they were in excess of the 51 votes needed for a victory. All 47 of the R votes were wasted, since their candidate lost. If you count up all those wasted votes over all the districts you have a measure of how many votes were wasted in a state. For instance if the Rs consistently win 80% of a state’s districts 53/47 and the Ds win 20% of a state’s districts 20/80, then the Ds waste a lot of votes both in the winning districts (80% instead of 51%) and in the losing districts (47%). When you apply this measure to real elections it quantifies just how much the Republicans successfully gerrymandered a partisan advantage in states like Pennsylvania or Ohio.
It’s a simple measure, but it’s still complicated to explain to people. So I took a crack at quantifying something even simpler, the gap between popular vote and congressional seats. For instance in North Carolina last year Republicans took 53% of the popular vote for House of Representatives. However they took 10 of 13 seats, 77%. That’s a pretty remarkable spread of 24%. That outcome spread is a different measure than the efficiency gap, much less subtle, but it’s one I think people can relate to pretty easily.
What happens if I add that spread up over all 50 states’ elections and graph it over time? I scraped data from Wikipedia pages and came up with this:
There you go. It shows that in 2016 the Republicans got 55% of seats with about 50% of the popular vote, a spread of +5%. Back in 1990 they got only 39% of the seats with 46% of the vote, a spread of -7%. It’s the spread between the two that I’m interested in, so let’s graph the spread directly:
Note the graph of the spread is more or less correlated with the blue line above, the % of seats the Republicans got. I’m not sure what that means but it seems important.
Visualization Failure: Oversimplified
My main conclusion from this exercise is it’s a failure. I’ve oversimplified. there’s no obvious story here. I think any fine point about redistricting gets lost in the broader story of swings between Republican and Democrat popularity.
I think it’s a mistake to add up the votes and seats across different states. Every state is a different story. North Carolina had a virulently partisan districting which probably explains its huge gap in favor of Republicans. California has an independent non-partisan commission designing its districts, so a different process, although the outcome in 2016 still seems somewhat to benefit Democrats (62% popular vote, 73% of seats).
It might also be a mistake to assume all Republicans and Democrats are the same. I mean as partisan as the United States has become, Representatives are still elected to represent a local community and in many cases are known to their constituents. Congresspeople have individual agenda and views and don’t just reflect their R/D affiliation.
For the last couple of months I’ve been reading a lot about redistricting, hoping to find a way I can use my programming skills to have some political influence. There’s a remarkable story in recent politics summarized in the book Ratf**ked; the Republican Party engineered a takeover in 2010 of the House of Representatives. Long story short, they worked hard to win state legislature elections in 2008 and 2010. This gave them control over the redistricting process in 2010/2011, drawing the lines for House of Representatives elections. That line-drawing worked, the cartography alone is responsible for something like 10% of the Congressional seats that the GOP holds. You get crazy things like North Carolina having 10 of 13 representatives being Republican, despite the popular vote for those seats going about 50/50. The GOP is quite explicit about what they did, too:
The state representative who drew that [North Carolina] map said he had engineered 10 safely Republican seats only “because I do not believe it’s possible to draw a map with 11 Republicans and two Democrats.”
I’m interested in the data and cartography part of this, the technical question. So I’ve been reading up. Here’s some of what I learned. See also Mike Migurski’s notes.
Maptitude: ArcGIS for politics
The key software tool used in 2010 is Maptitude for Redistricting. It’s a GIS tool specialized for redistricting. It comes preloaded with demographic data, election data, and political boundary shapes. It lets you draw district plans and see what the result is. Think of it as ArcGIS but for political scientists. There are many demo videos online.
An individual license for Maptitude costs $700 on Amazon. Mostly they negotiate sales contracts for group use, Ratf**ked suggested it was $5000-$10,000 for a state. Compare $500,000 for previous software from the 1990s.
Maptitude is by Caliper Software. They seem to have a democratic mission, putting redistricting tools in the hands of ordinary people. In 2011 they even made a web version for communicating to voters called Maptitude Online. Several states bought and deployed it: Maryland, Idaho, Wyoming... None of those 2011 apps still work, the backing server seems down. But there’s video online. It’s a pretty clunky web UI, from the era when people compiled their Win32 C++ GUIs to Javascript and called it a day. I imagine the 2020 version will be much more Web native. But it does work to genuinely communicate redistricting to people on the Internet.
Political data
One nice thing about Maptitude is it comes with political data that you buy from them. But it’s all proprietary and expensive. What about open source / open data hacking? Wanted, for every state, for every election every 2 years:
Shapefiles for each voter precinct. The voting precinct is the smallest building block of election data. You can’t find out how an individual voted in the United States, but you can see how a group of ~25-300 people in one precinct voted.
Per-precinct vote tallies for every major national election. President, Senate, House of Representatives. State legislature data would be nice too.
Shapefiles for every House of Representatives voting district. These are typically, but not always, the union of precincts. State election districts would be nice too.
America has no centralized election system. There is no simple database of election results, political districts, etc. Particularly not for data as detailed as per-precinct results. Every state maintains their own data. Some states publish nice clean CSV and Shapefiles. Some states will send you a scanned handwritten ledger if you call and pay a $4.95 document fee. It’s a mess. Here’s what’s available for open use.
OpenElections collects election returns. It came out of a data journalism product and they are doing good work towards a 2016 set but it is a long process.
election-geodata is a project headed up by Nathaniel Kelso which collects precinct and district shapefiles. It’s not complete but has gotten a whole lot of data, particularly for 2016.
Between those two projects I think we have ~75% of 2016’s election in easy-to-use format.
Also worth reading: Mike Migurski’s work on North Carolina elections, where he goes through the exercise of collecting and analyzing the 2016 election for that state. It’s a model of what I’d like to be able to do easily for every state and every election.
Demographic data
I haven’t researched this much yet, but the other half of redistricting is understanding the demographics of the people you’ve put into the districts.
Census data is the basic data standard here, free and public and easy to work with. It comes broken down by census blocks, groups of 0-500 people. Those blocks do not line up with voting precincts, so some slicing and joining is required to produce per-precinct views of census data. Migurski did this for North Carolina.
Marketing data is the other interesting option here, and a total black box to me. But all of the tracking tools that enable direct sales and Internet advertising are producing data that’s a political goldmine. I suspect little to none of this data is available for free open hackery. News articles about the 2016 campaign are full of stories about how various political groups used this data with varying levels of effectiveness.
When I started this research I had no idea something like Maptitude existed. I thought maybe I could help build a GIS-for-elections and revolutionize politics. Ha! I’m at least 10 years too late on that. The state of the art in 2011 was a tool that let political experts draw district plans and then understand with great detail how those people voted in recent elections and therefore, how they would likely vote in the next election. What about 2020?
Demographic prediction. District plans last ten years; you can design a plan that looks great for your party in 2022 only to find it fails in 2028, what is called a “dummymander”. Predicting demographic trends sounds like a good data problem. There’s a lot of expertise on this already.
Automated districting. I get the impression 2010 districts were still mostly hand drawn. But computers can easily produce zillions of plans. It’s a problem ripe for optimization algorithms.
Smarter measures of gerrymanders. This topic is hot politically now, particularly a new measure called the efficiency gap which quantifies the partisan bias in a district plan. Communicating these measures to the voting public seems really valuable.
The hard part for me with all this is I’ve rapidly learned that redistricting is not a technical problem, not something I can program a solution to. It is a political problem. People with political expertise and power are going to set the agenda. But software is a tool for that politics, maybe a tool I can help craft.
Played with Fog of World today, an iPhone app that turns GPS tracking into a game. It records where you go and then paints the map, “lifting the fog of war” in videogame style. It’s heavily gamified; lots of badges and stuff for exploring more of the world. I love the idea of this kind of thing, my previous experiments with mapping walks I took is in the same vein. Also GPS tracks for my private airplane flights.
The engineering is pretty good quality. It has very thoughtful import/export options, including a nice integration with Dropbox. Map rendering is pretty good. Plenty of care applied to battery management.
I’ve been running OpenPaths for years, recording my world travels. It took about 5 minutes to export that data to KML and import it to Fog of World and boom, I’m level 75 with a filled out passport. Unfortunately OpenPaths only records point locations every few minutes, not full paths, so I have a bunch of little speckles of revealed parts of India rather than a clear path on a trip. Fair enough.
I also imported my RunKeeper data from my old walks project. That gives much smoother paths. The display is still kinda janky though, if I were building this app I’d give paths more width and smoothing. That or else try to do some scalable measure, where if I’m looking at a whole country map I see all of the Bay Area filled in, but then I can zoom in for more detail.
Update: this app seems to be killing my battery. The usage monitor in iOS only shows it using 20-30% of my energy, but having it running is the difference between a 5% battery in the morning vs a 60% battery. At least I thinks it is.
I’m trying Strut now, a similar thing, but much more heavily focussed on competition. Also no import / export :-( But it is free. (Update 2: it’s even harder on the battery than Fog of World). Also while researching all this I found a nice comparison of Fog of War v1 vs v2.
Justin Meyers did an awesome treatment of OpenAddresses data. He put all the points in QGIS, then binned them by county, then put the shapefile in a repo. Nice! I wanted to see what the data looked like normalized by population, so I did two treatments. One is kinda sorta logarithmic, the other is a simple linear scale capped at 2 addresses / person.
Logarithmicish
Linear, capped at 2
I’m not quite sure what this visualization really shows. I was hoping it’d be a proxy for data coverage; like naively I expected there’d be one address per person, more or less. But that’s clearly not what I’m seeing here. The Montana outlier is particularly baffling, there’s 10 addresses / person in many counties.
Via my friend Amit, I think someone has finally built the map I wanted so long ago. Rivers in the US colored by stream flow. I’m not quite sure what the data is, at least some of it must be models rather than measurements. But it’s good.
The map is at the NWS Enhanced Data Display. It’s some clunky Windows-GUI-in-Javascript thing. But the data is great! The layer we want is under “More Layers / Rivers / Nat. Water Model - Stream Flow”. I set the base map to ESRI Light Gray to see the river layer better.
Michal Migurski is working on a new project, rendering previews of OpenAddresses datasets in slippy maps. We’re using S3 to store stuff and trying for stateless servers. He just described the architecture plan to me, I’m writing it up here. He’s doing all the work, currently in a test git repo. The fun part is a FUSE file system for MBTiles on S3. Read on.
OpenAddresses is a collection of address data points. Big CSV files full of latitude, longitude, street name. We collect the data from government sources. Every time someone finds a new government source they create a pull request like this one for Luzern with metadata for the source; stuff like the URL and how to parse it into our format. Mike has some GitHub integration hooks that look at the pull request and renders a preview image of the data file. It looks cool, but it’s also a useful debugging tool. We’d like to transform that static preview image into a slippy map. Here’s how it’s going to work.
GitHub integration hook: use Tippecanoe to boil down the address points into a tiled dataset. Write the resulting MBTiles file to S3 somewhere. Note this hook and processing is on a transient server that disappears once the processing is done.
Web page: slippy map using Leaflet or the like to request OpenAddresses tiles and render the points in the browser.
Tile server: a FUSE filesystem that mounts the S3 MBTiles file and provides it to TileStache.
It’s that last step that’s particularly clever. Serving an MBTiles file locally is easy. But what do you do if your MBTiles file is on S3 somewhere? It might be quite large, 10 million points or 100 megabytes. But each map view only needs like 16 tiles or a megabyte of data. You’d rather not have to copy the whole thing from S3 first.
So instead of caching the whole file locally, Mike has written a simple read-only FUSE driver to remotely mount the S3 file. To normal Linux processes it just looks like a file, but behind the scenes read requests are being turned into HTTP Range-restricted requests to get the bytes and return them.
Why go through the hoops of FUSE? The challenge here is MBTiles are actually Sqlite databases, and Sqlite really wants to open an actual file down in the depths of its highly optimized C code. So we give it a file.
The big question here is performance. It seems to be OK on first testing! Sqlite should be pretty efficient about reading data. I’m a bit more concerned about llfuse, the Python FUSE driver framework Mike is using. It seems to have a single global lock so only one S3 read request can be active at a time, maybe per mounted MBTiles device. So this might not work so well; in practice multiple tile requests are happening in parallel, even for a single user looking at a single slippy map. But we don’t imagine many users so it may not be too bad.
We’re about to get a lot of rain, and like every year I get interested in the local rivers and waterflow around Grass Valley, CA in Nevada County. Here’s some rough notes and resources.
Yuba River, particularly the South Fork
Yuba River at Marysville: flow history and forecast. This is below Englebright Dam, so includes the choices of how much water they’re releasing there. But is excellent data from NOAA.
Yuba River at Jones Bar: flow history. From CDEC. This is either the exact same sensor Dreamflows is showing at Highway 49 or else is a mile downstream.
Yuba River flow history along the whole river. This is California state data (CDEC) and the website has lots of neat stuff.
Wild and Scenic River Act protects the river from Lang Crossing to Bridgeport. This is the much loved stretch of scenic river with lots of swimming holes, etc.
Deer Creek is literally 500 feet from my house and, fortunately, 100+ feet below it. I can hear it rushing all the time, but have to hike/drive to see it.
Best of all, here’s the data! Very nicely prepared for use. I tossed some of the California occurrence GeoTIFFs into QGIS for a quick plot. This view is centered on Engelbright Dam with Sacramento to the west, where the American and Feather rivers meet. Blue is year-round water; pink is intermittent (and seems to highlight farmland.)
At a scale of 30m per pixel this dataset doesn’t show small rivers or creeks. But what this map does show is the history of water over 30 years of Landsat imagery. In addition to the basic occurrence map there are also several data layers highlighting changes in the surface water. One showing before and after Jan 1 2000, one showing seasonality, one showing yearly recurrence, and some other more technical measures.
It’s a solid piece of work and nicely packaged. And all free!
I got curious about the details of the Hawaiian Homelands geography so I made a slippy map version. Patience on the first load; the basemap takes awhile. Purple overlay are the homelands (click for name), white lines are the historical Ahupuaʻa divisions. The basemap is Mapzen’s Walkabout style, a nice terrain map.
I’m feeling super ignorant looking at this data without really understanding the history or current situation of the Hawaiian Homelands. A friend recommended the book Hawaiian Blood. As a humble mapmaker I realize really what I need to do is work with an expert on Hawaiʻi, keep myself confined to journeyman geoprogramming.
But anyway I looked around, some interesting sites:
Waimanalo on Oʻahu. I love this shape, the terrain map shows how it tracks the ridgeline.
Honokawai. Google’s aerial imagery shows the hole is a reservoir. Not sure about the meandering slice out of the middle, it looks like a wooded ravine or river.
Waiohinu. Some individual parcels in a golf course development.
Airports: Hilo and Kalaeloa. It looks like the airport was dropped on top of the homeland, I have to think there’s some history there.
Production notes
I cobbled this together starting with Mapzen’s excellent one minute map tutorial. They’ve built a Leaflet extension that makes it super easy to add Mapzen’s base maps (vector rendered!) and map search. On top of that I just added a couple of custom GeoJSON layers with Leaflet-AJAX.
I made a map of Hawaiian Homelands. This Reddit post about a map of American Indian Reservations and Alaska Natives inspired me; it left off anything about Hawai’i. The history of native Hawaiians and land ownership is totally different from the history of American Indians on the mainland. But the Homelands are somewhat analogous to Indian reservations in that they were land set aside by the US government for native people. I don’t believe they have any form of partial sovereignty though, and I think these land are even more sparsely populated than mainland reservations are.
Anyway, really I just wanted a nice picture; this one was the best I could find online. So I spent an hour or two with QGIS and came up with the image below (see full size). Totally unfinished draft, but this here is my secret work blog so up it goes.
The green shapes are the Homelands themselves, the point of the map. I drew in major roads in orange to try to give some context to location. I wasted a lot of time trying to draw a few labels for towns but Oʻahu is so densely populated no simple rule works. I’d need to place town labels by hand for it to work right and I got lazy.
I also rendered the historical Ahupuaʻa in very light grey. That’s a fascinating division of the land from historical property rights. They seem to have been designed to give each owning aliʻi a mix of lowlands and highlands, with both farmland and some forest. I’d wondered if the Homelands followed the old ahupuaʻa boundaries but I think mostly not, except for the one large one in South Maui.
I wouldn’t mind spending more time to make this publication-quality. But I’m so ignorant of what the Hawaiian Homelands really are that I don’t feel comfortable doing any interpretive mapping. OTOH the Wikipedia page would benefit from any sort of picture, even this simple one, maybe I should look into what’s required to submit there.
For two years I’ve had an Automatic tracker in my car, a gizmo that downloads data off the diagnostic port and uploads it to an iPhone app via Bluetooth. It tracks things like speed, mileage, etc but it turns out the most interesting thing it’s actually tracking is where I drive. But it’s not that interesting, and I’ve always been a bit nervous about the privacy implications of it, and rather than pair it to my new phone’s Bluetooth I’m going to stop using it.
Some summary stats from it:
613 trips since September 2013
11,290 miles in 252 hours. Average speed: 45mph.
25 MPG average, $1600 in fuel
By far most of the hours in the car have been the 150 miles on I-80 between SF and Grass Valley.
The main use case the developers have in mind seems to be a nanny to encourage you to drive better. You get a “Score” that’s dinged down for driving over 60 mph, or braking too hard, or whatever. I found that condescending and useless. The IFTTT integration was sort of nice for creating data in Dropbox, but it wouldn’t export the GPS track. The product got a lot more useful when they added the Dashboard, with some nice Mapbox views of the data. Still I don’t have much use for collecting the data.
Here’s a heatmap they produced of all my driving. You can see all the I-80 trips, plus a long trip down to LA and back. Occasional detours through Stockton or Yuba City.
A question inspired by my work on OpenAddresses.. How many addresses are there in the world? By “address” I mean something that should be geocodable to a specific lat/lon, like 1600 Pennsylvania Ave NW, Washington, DC 20500. Normal people might define an address as something you can get mail delivered to, or tell a taxicab.
One address per two people. That’s the estimate Tom Lee came up with by comparing sizes of OpenAddress data we have to population. It’s not a bad estimate!
The confounding factor is that “address” is a somewhat first world concept, I imagine there’s fewer unambiguous addresses in rural / third world places. There’s a lot of the world where naming locations is much more loosely defined, “go to Tegaljaya village, go towards the mountain from the crossroads, turn left at the big banyan tree, and then five houses down”. OTOH I think every country in the world has mail delivery, which means there is some sort of system for finding people. Should do more research.
Someone asked me to give them a map of all the rivers in the state of Ohio. Sounded like a fun PostGIS exercise for me. Unfortunately I’ve made it more complex because my river database is in SRID 900913 by default, so intersecting that with the Natural Earth admin1 data in a different SRID is not as simple as a one line query. I could just transform Natural Earth on import but ogr2ogr pretends to not know 900913 and that seemed bogus anyway. Some notes from my goofing around:
-- state boundary data is in EPSG:4326
# select ST_SRID(wkb_geometry) from admin1 limit 1;
4326
-- Coerce the test point to the SRID that the state boundary data is in
# select name from admin1
where ST_Intersects(wkb_geometry,
ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 4326));
Ohio
-- try querying with a point inside Ohio but with mismatching SRIDs
# select name from admin1
where ST_Intersects(wkb_geometry,
ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
ERROR: Operation on mixed SRID geometries
-- Coerce the test point to 900913, which should not work.
-- Bafflingly does not give an error for mixed SRIDs, just returns 0 rows
# select name from admin1
where ST_Intersects(wkb_geometry,
ST_Transform(ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'), 900913));
(0 rows)
-- Coerce the state boundary geometry to the test point's SRID
# select name from admin1
where ST_Intersects(ST_Transform(wkb_geometry, 4269),
ST_GeomFromEWKT('SRID=4269;POINT(-82.98 39.98)'));
Ohio
A bunch of artists all recently have been asking me for scalable vector versions of my river map. A very reasonable request, given the data is natively vector, but all my renderers have been browser-based pixel things. Fortunately the underlying rendering is done with D3, which creates SVG in the browser. So how to save it?
Saving SVG
The simple answer is the SVG Crowbar Chrome bookmarklet. This lets you take, in essence, a screenshot of what’s in your browser but in SVG vector form. I think it’s basically copying and pasting the SVG out of the DOM, but it’s got some cleverness about keeping stylesheets too.
The real answer is some proper SVG writing code. No one seems to have ever really done this in D3 nicely, I think you still need something like the Downloadify Flash shim to enable the browser to write the file. (The very newest version of Chrome does have a file writer, but it’s part of the Mozilla work on editable web pages and seems weird.)
Another proper answer is to bypass the browser entirely and write a Node headless program to create the SVG and write it. I gather JSDOM is the library of choice for a browser-like DOM environment in Node, worth a try.
Resolution
Unfortunately I don’t know much about working with SVG. Everyone wants to edit in Illustrator but I don’t know or own Illustrator. I’m told my SVG Crowbar files do load in Illustrator, so I guess that’s good. They do work in Inkscape too but I don’t know Inkscape very well and it’s pretty clunky.
Anyway, my SVG question is about scale. I’m used to tuning the way things look for pixels. For instance, for river maps for rivers of Strahler 1-10 it looks good if the line width is about strahler/2.0 pixels wide and I render the US to about 2000x1000 pixels. That’s what I did in the one goofy raster image that got Internet famous.
But pixels are lame. What if someone wants to print to a 20′ wide mold for a sculpture? (This is actually happening!) Or make a fine letterpress print (also, happening!) I’m hoping for now the Illustrator jocks can just scale the line width, etc as they need, but I don’t know what’s right.
Resolution independence also raises questions about coordinate rounding, and simplification thresholds, and other details.
Migurski and I have been working up a new architecture for OpenAddresses, specifically the python code that runs source jobs. Currently everything runs as a big batch job every two days. The primary goal is to get a system that can run a new submitted source instantly, ideally with useful feedback to the submitter.
Mike’s insight was to build a system a little like Travis; something that looks at GitHub commits with a hook, runs a new job every time something is committed, and posts back info via the GitHub status API. GitHub is nice because it provides a file store and change tracking. Ultimately we don’t want to require a GitHub login to submit sources, and we probably want a custom UI, but that can come later.
Here’s the components we’re talking about building:
A GitHub webhook that submits info to our new job server when stuff is checked in.
A new job server that accepts HTTP posts of GitHub events. Mike’s got one working in Flask running on Heroku.
A job queue. New jobs get enqueued by the new job server, then some worker daemon process checks for jobs to run and executes them. Can be a very simple queue, but needs to support job priorities (interactive vs. batch). Right now I’m thinking of writing my own using Postgres running in Amazon RDS, but there’s got to be something I can just use that’s not super overkill. (Update: pq looks good.)
Workers to run jobs. Something to look for new jobs and execute them. Current thought is a persistent Unix server running on EC2. Installs openaddr and its dependencies via pip, then runs jobs via openaddr-process-one, then posts results back to the job queue result queue.
Job completion notifications back to GitHub using the GitHub status API. Mike has been tinkering with code to do this already.
A batch-mode refresher. Something to run sources periodically even if no one’s edited the source specification in awhile. Mostly to catch new data on the remote server.
Here’s some open things to design.
Job status reporting with humane UI. Currently we get very little info back from when a job is run. A few bits of status (did it complete, how long it took), a debug log from the process, and any actual output files. We need more. In particular I think the stuff you currently learn from the debug log needs to be expanded to useful user-level event data. Ie, events like “source JSON parsed”, “source data downloaded”, etc.
UI for creating source specification JSON files. Imagining some guided wizard like UI using Javascript and forms. There’s already a pretty good one on the live site, just needs some expansion. Also ultimately we shouldn’t require a GitHub login.
Security. A bit nervous running completely unreviewed source specs from anonymous people. Isolating the worker in a throwaway machine might help. Or doing some sanitization on inputs.
Statistics reporting. I have a dashboard that works OK for the existing nightly batch mode, but we’ll want something different for this continuous mode thing.
See also OpenAddresses Mark 3, a proposal I sketched in January. What we’re doing here is similar but without the component of breaking any individual source run up into separate tasks.
Some stuff of possible interest to OpenAddresses. The US government’s Federal Geographic Data Committee standardized street address schema. The docs are 140 pages of text describing an XML schema, which sure seems wordy, but then it’s also very precise. They even put the XML schema online, here’s a text rendering.
It’s super wordy and contains a lot of detail, but at the core is a schema we could repurpose that says things like “a street address consists of a number, a prefix, a street name, ...”
There’s a good summary of the schema on page 3 of the executive summary. Here’s the meat of it:
For each run, print out how many sources we tried, how many cached, how many sampled, and how many processed. The counting here is a bit bogus but I think close.
Some rough notes for optimizing openaddresses conform. These times are from a January 23 run of the Python code. The machine was busy running 8x jobs, so times may be a bit inflated from true, but it’s a start.
Here’s 3 sources that I know to be slow because of our own code. The time reported here are purely the time doing conform after the thing was downloaded.
??? ESRI source. No good examples; most of my conform code treats this as effectively CSV anyway, so going to ignore for now.
I just ran nl again and it took 31.5 minutes (26 minutes user, 5 minutes sys). Close enough, I’ll take these January 23 times as still indicative. At least for CSV sources.
Here’s some fast / short sources I can use for testing. These are total times including network.
us-ca-palo_alto.json (csv source) 26 seconds
ca-bc-north_cowichan.json (csv source) 24 seconds
us-wa-chelan.json (shapefile source) 33 seconds
And here’s a report of top slow jobs that didn’t actually time out. Some of this slowness is due to network download time.
For a CSV source, we spend roughly half the time converting source CSV to extracted and half converting extracted to final output. That’s no surprise; the two CSV files are nearly identical. A whole lot of that time is spent deep in the bowels of Python’s CSV module reading rows. Again no surprise, but it confirms my suspicion that DictReader may be doing more work than we’d like.
For a shapefile source, we spend roughly 2/3 of the time using OGR to convert to CSV and 1/3 of the time converting the intermediate CSV to the final output. The OGR code is opaque, not clear how to figure out what it’s really spending time doing inside the C module.
Not clear what conclusions to draw here; there never is with profiling tools. I think my next step should be benchmarking Python’s CSV DictReader and seeing whether some simpler parsing would work significantly faster. I also think it’d be a huge improvement to remove that intermediate CSV file entirely, there’s a lot of overhead reading and writing it. It makes the code way simpler to work with but it should be possible to stream the data in memory and retain most of the same code model.
Not clear any of this optimization is worth the effort.
Kinda like how chaotic and pretty this graph is. It’s memory usage on my dev server for the past week, as I kept doing big OpenAddresses runs stressing the system. No huge insights, just looks neat.
I’m re-running OpenAddress many times trying to be sure the output stays roughly consistent. It’s never the same twice; servers are unreliable and the data is changing. Also some code changes make small cosmetic differences like rounding error.
What works best for me is comparing the line counts in the output files:
This only highlights sources that output different number of lines; if the contents in the columns is garbled you won’t see that. But it’s a good way to get an overview of what changed between two runs.
When I’m back from India late February I’d like to re-design OpenAddress machine to a more decoupled architecture. Right now the system runs one big Python process which runs all sources from download all the way to output CSV. (There is some state carried over from run to run, but not much.) It works pretty well and is simple, and a full run just takes 2–3 hours. But the multiprocessing stuff is brittle and the whole system is both overkill (most sources never change, why reprocess?) and also non-responsive (no fast way to test a new source).
Proposal
Move to a decoupled architecture where tasks are run as fully independent Unix processes. They share state via some centralized database / cloud storage thingy, and also post results in S3 for web serving.
As with the current architecture, the unit of work in the job system is a single source file such as us-ca-san_francisco. It runs as an independent Unix process with no awareness of other sources. It downloads, conforms, summarizes, reports, and uploads its results to the database and to S3.
In addition we also need a task queueing system, something that decides when to run source jobs and posts them on the task queue. That process works mostly by reading the database and deciding what work needs doing. Some rules: “immediately process a new source”. “Check a source weekly for new data and reprocess”. “Clear the whole queue and re-process it”.
Finally we need a task executor that looks at the queue and launches tasks as needed. This could be part of the task queuer, but it helps to think of it as a separate entity. When a task is finished it puts the result on the task record log.
Database implementation
I’m totally agnostic about the data store we use to track runs. It’s a very low demand system just a few hundred megs of data and a handful of transactions a minute. It will require something with consistency and responsiveness. The simple choice is a PostGIS database running persistently on some 24/7 server. I’m not sure what the cloud services equivalent would be, so running with the PostGIS idea, here’s some schema sketches:
There’s a zillion ways to do a task queue in a database. Rows are placed in the table by the task queuer, then removed by the task launcher when they are dispatched.
Task implementation
A task should be a single Python program. It takes a source.json specification file and any job metadata that’s needed (hopefully none?) and executes it. For debugging purposes this program should be able to be run standalone on a developer’s machine with no dependencies on the queuing system, the task manager database, or S3.
These jobs will be a natural to run on cheap EC2 spot instances. Right now tasks take 0.5 – 90 minutes to run. A bit wasteful to spin up a whole EC2 instance for 30 seconds of work, but maybe that’s OK. We could also run tasks on a single workhorse machine, that’s effectively what we’re doing now. A single mid-level Linux box can run 16 tasks in parallel. (In fact parallelism is good; the jobs are a mix of load types.)
Alternate: subtasks
This proposal assumes that a whole source from start to finish is run as a single Python process. But in fact processing a source consists of several sub tasks, and it might be good to run them as separate sub-tasks. Here’s what the subtasks are:
Download from source URL / ESRI store
Sample the source data for user inspection
Convert the source JSON/CSV/SHP data to an extracted.csv file
Conform the extracted.csv data to OpenAddresses out.csv format
Upload out.csv and job data to S3
There’s times i’ve wanted to be able to execute these subtasks separately. Particularly the download part, that is slow and unreliable. To some extent the current data caching strategy in Mark 1 and 2 is dealing with that, and it may be sufficient. But you could imagine breaking every source into 5 tasks and running them separately on a job queue. Worth considering.
History
Why “mark 3”?
OpenAddress Machine mark 1 was Mike’s original work, wrapping the Node code in a bunch of Python scripts to do regular runs and post results in a web dashboard. It is awesome.
We’ve been working on mark 2, the “ditch-node” branch, where we rewrote all the Node code in Python. The overall job architecture is about the same as mark 1, the management of downloads and files and stuff. It’s one big Python process with jobs run in parallel using multiprocessing. We did make some changes to how tasks are conceived and run.
Updates
Some notes after this post was written
Ian notes that GitHub triggers and Jenkins could trigger a build on a new source
After the first run against 600+ sources we patched up a bunch of bugs, improved the running infrastructure. Then I ran another set last yesterday, amended a little bit today to re-run jp-* and kr-* after one more bug fix. I wasn’t quite as careful in measuring everything, but here’s some notes on output.
102M output rows.
Compare 80M from previous run, 100M from Node
Roughly 3.5 hours running time, maybe less.
3 threads stalled on bad servers so it’s not a good measure.
Throwing out the 3 stalled runs, the average source took 137s to execute. Standard deviation of 585s, so it’s a very broad distribution. That first run averaged 104s (SD 265). But a lot more of those runs failed in 1 second!
I’m curious if the new ESRI code is faster or slower than the old code. It’s definitely better in that it works with many more sources. Don’t really have data for it. The ESRI time is probably dominated by slow servers anyway.
Here’s the slowest non-ESRI sources. Given that these times include download times from some slow servers I’m pretty OK with them.
95 sources failed to produce an out.csv. Of those, 7 did succeed last time we ran, a potential regression. Here’s the cause of each failure:
us-il-tazewell: ESRI source, JSON parsing error after many calls
us-tx-colleyville us-tx-dallas us-tx-hurst: ESRI sources, found no records
us-nc: missing “file” attribute for multiple shapefiles
us-dc: bad download
us-ca-san_diego: bad zip download
And finally here’s the list of all 95 sources that didn’t produce an out.csv. I should go through and hand-classify the failures again, but I bet most of 88 of them are for the same reason as last time.
Here’s how long it took to process each source. No idea how much of this time was network, how much processing, etc. Painful irony that many of the slowest ones were the ones that didn’t work. There’s no job-level timeout.
206 of the 608 sources I tried with the new Python code didn’t work. I went through and hand-classified them by type of failure. (Related: we need better error reporting in the code, I could only do this by reading stderr logfiles and guessing.)
I’d guess about half the failures are problems with the source not being online at the time. And maybe only a quarter of the problems are bugs in the Python parsing code. But not sure without looking more closely.
Update: I triaged and either solved or filed issues for the following failures:
Parser doesn’t handle malformed CSV
Parser doesn’t handle GML files
Excerpt failed (partial fix; the conform continues)
After a couple of weeks of steady work the Python code to process OpenAddresses is nearly feature complete. I did a big run last night over all the sources we have. It went well!
80M out.csv rows. (Compare 100M from the Node code)
3 hours, 5 minutes running time
< 16G RAM running 8x parallel
11.5G of useful output files
100+G disk used (temp files left on error)
7G of cached source data: 3.5G zip, 3.5G json
150Wh = $0.50 of electricity
Operational behavior
I ran the whole thing with 8x parallelism using GNU Parallel on my Linux box. The box is nothing special; a quad core i7 with 16G of RAM and a very ordinary 7200RPM hard drive. Home network is 100Mbit for downloads.
I think disk contention was the primary bottleneck, an SSD might make a big difference. So would keeping data in RAM while we process it, I think I overwhelmed the disk cache. FWIW the disk has a benchmarked performance of about 120 MBytes/second. But having listened to the thing, there was an awful lot of seeking going on. Parallelism isn’t friends with a single spinning drive.
Below are some munin graphs for the day of the run. There’s two runs here; an aborted run to the disk sda (which filled), then a successful run around 04:30 to 07:30 to the disk sdb. Not sure the graphs have a whole lot of information. They do show some serious IO contention; the CPU graph shows as much time spent in IO wait as doing actual work and disk latencies hit 500ms for awhile there, ugh. The memory graph is too messy to read but I do know the system never needed to swap.
I want a simple tool to reproject a crappy whole-sphere image like this to something nice like Mollweide or Winkel Tripel. It seems like this would be easy enough with gdal, just have to learn enough about CRS to do it. The source looks like Plate Carree, no doubt produced by someone naive with a raster array of lat/lon samples.
Got a decent looking work print of a map of all the Australian rivers, as inspired by Chad Ajamian’s map. It’s on Imgur as a JPG, wordpress.com seems to have done a reasonable job with the full PNG, compressed it better than I can (!).
I produced this in TileMill, using data imported to PostGIS with ogr2ogr. I hoped to use the new MapBox Studio but it’s kind of a pain. Working with local data sources is awkward and there’s no simple exporting to a hires image. TileMill still gets the job done, what a champ! QGis also works and is faster (caching?), but its pixel rendering isn’t as beautiful as TileMill’s.
Map is styled on two parameters. Color is brown or blue depending on whether the stream is perennial, line width varies by UpstrGeoLn, the length of all line segments that contribute to this line segment. That’s not a bad proxy for stream importance, actually, I’m using it in lieu of Strahler number. I like the results.
Here’s the relevant part of the TileMill style sheet.
Here’s a new one on me; I used ogr2ogr to import the Australian river data into PostGIS and it ended up being labeled with SRID 900914. WTF? According to this discussion that’s what ogr2ogr does if the SRID isn’t already defined in the PostGIS tables. It adds a new entry with the CRS info gleaned from the source file. And since the largest defined SRID in most PostGIS installations is 900913 (the bogus Google entry) why, the next one created will be 900914.
The data is actually in EPSG:4283 which PostGIS already knows about.
While I’m here, this Stack Exchange answer has some useful ogr2ogr flags for big imports. -progress and --config PG_USE_COPY YES. According to the docs COPY may now be the default, but I’m not sure it is. Adding it cut my running time to 20% of without.
So the Australian river database doesn’t have Strahler numbers for streams, which I need to classify streams in order of importance. I got a very nice reply from the AHGF team asking about Strahler number with some ideas on what to do.
One option is to classify on a different measure. AHGFNetworkStream has a couple of features that are useful; UpstrGeoLn and UpstrDArea. They are “Combined geodesic length of contributing upstream AHGFNetworkStream features (incl. segment).” and “Combined albers area (m²) of contributing upstream AHGFCatchment features (incl. segment).”, respectively. Ie: how long the line is that feeds into this line, or how big the area that feeds into this line. It’s worth a look. Of course what I really want is actual water flow, but that’s not readily available.
The other option is to calculate the Strahler number myself. It seems like a simple enough algorithm. As long as the data is clean, that is, a strict tree. The AHGF folks warned me their data has loops and splits that might cause problems.
GRASS also apparently has some Strahler calculations. (Or Horton, which is similar. “Stream order” is the generic term.) More details here. I wonder which is easier; using GRASS or writing my own code? :-P
Inspired by this map of all Australian streams I’m taking a crack at extending my rivers map to Australia. There’s a great open data site which has what I need, sort of.
I’ve found two different layers that are likely candidates. I think what I want is AHGFMappedStream from SH_Cartography. There’s also a AHGFNetworkStream in SH_Network but it has slightly fewer entries and also has stylized geometries.
Here’s an image zoomed in near Strahan in Tasmania. Brown is the network view, blue is the mapped view.
Hierarchy appears to be only “minor” or “major”. “Perennial” is an interesting field.
Unfortunately what I can’t find is the Strahler number of a stream. I need that, both for nicely rendering bigger streams in heavier lines and also to simplify when zoomed out. I think I can figure out calculating it myself (using NextDownId on the table) but it’s a pretty big project. May be easiest to do that on the Network layer; it appears I can join across layers on HydroID.
$ key="HIERARCHY"; ogrinfo -al -sql "select $key from AHGFMappedStream" *.gdb -geom=no | head -100000 | fgrep "$key" | ~/src/accumulator.py
29682 .8906 HIERARCHY (String) = Minor
3646 .1094 HIERARCHY (String) = Major
1 .0000 HIERARCHY: String (0.0)
Here’s the full schema. The site has some PDF docs that are helpful too.
I brought my vector rivers map back online. It was a casualty of my server meltdown a few months ago, and I thought that no one really used it and it requires 3 daemons to work and it was a pain so why bother? I put a note saying “email me if you miss it” and every couple of weeks someone wrote, so I felt bad and finally fixed it today.
Code rots. Fortunately this didn’t rot too badly. All told took 5 changes (see Dec 2 2014 a7a9424..77debec), 14 lines. And a bunch of stuff to install, although it’s easier now in Ubuntu 14.04 which has newer versions of PostGIS and pgdbf.
Ubuntu’s localhost randomly is [::1] instead of 127.0.0.1, but Gunicorn doesn’t bind to this. Damndest error, random failures. This blog post helped me figure it out.
It’s funny I never thought of the actual river maps themselves as my product, but rather my nerdy code project. I suspect at most two people have gotten my code working themselves, so that was a failure. But a lot of people like looking at pretty river maps. I should make an effort to make an even prettier one, just for the aesthetics.
Other project is to productonize the thing, specifically startup scripts and logging for Gunicorn. Kind of a PITA, may not bother.
I like making slippy maps that fill the browser window. Every time I do this, I forget how to do it right. It’s easy to screw up and make a map that causes the window to have a vertical scrollbar, or that doesn’t fill the whole window. Firefox used to have a different CSS model which caused some of my maps to only fill the upper left of the window, like 2 map tiles. Chrome recently changed and now my maps are broken that way in Chrome. Here’s a screenshot of how it looks:
So how to fix it? The notes below are only testing desktop Chrome 37.0.2062.124 on a Mac. This d3noob block has a full window Leaflet map that works well and is simple. The crux of it is
If you don’t set the margin on the body to 0, then Chrome’s default is an 8 pixel margin on the entire body and you end up with scrollbars because the 100% map now hangs 8 pixels off the window. The padding: 0 may not be necessary; Chrome’s default seems to be no padding on the body already. But it’s harmless and seems like a good idea for a full reset.
It’s also common to see overflow: hidden on the body, to suppress all scrollbars. I think that’s also harmless and even possibly a good idea, but is not strictly necessary. It also causes problems for other full screen webapps that aren’t maps. Logs of Lag has a “natural” height of about 800px. I used to set overflow: hidden to work around a scrollbar bug, but then that broke the case where the window is shorter than 800px and you really do want a scrollbar. Not something that’s likely to come up in a map, but maybe in other full window app contexts.
The height: 100% must be set on all of html, body, map. If it’s not set, then the height calculates to 0 and you end up with nothing displayed. The width: 100% seems unnecessary, you can remove it entirely and it still renders full width. But it seems harmless.
I wasn’t able to reproduce the “show only two tiles” brokenness in my screenshot above in Leaflet with a simple example of a page with just a map div. It may be not possible any more, not sure.
The bug is showing up for me with my Polymaps maps though, even if I set all the widths and heights and stuff as described above. Turns out for Polymaps you also have to set the size of the SVG that you put inside your map div. I did this by hacking in a svg { width: 100%; height: 100%; } in my stylesheet, which obviously only works if you have no other SVG elements on the page. Since Polymaps is long since EOL, there’s not much point trying to figure out anything better.
JeffN was kind enough to point out the new Automatic Dashboard. Automatic is a gizmo that plugs into your car service data port and relays data to an iPhone app. It records fuel usage, speed, GPS track, etc. Neat data, but the presentation has been really limited so far to a mobile-only experience. Well now they have a webapp and it looks great.
trips returns an array; one example element below. I’ve zeroed some of the IDs. The path data is most interesting to me. It looks to be pre-encoded as a polyline, which the javascript renders in SVG. It doesn’t load more detailed data when you zoom in, I think this is it. A bit of a hassle to reverse engineer this to normal lat/lon data, but it’s probably all some standard MapBox data format so should be possible. Update: apparently it’s the Google Maps polyline format.
The graphs are nice. They’re SVG and I see nvd3 is loaded in the page, so I assume that’s what they’re using.
Moved by Bobby Sudekum’s map and this Ask Metafilter question I drew a quick heatmap of all the places I’ve been in the past two years. Primary data source is OpenPaths, 6348 location points. Results in the gallery.
Bay Area livingSan FranciscoVegas to LA roadtripNorthern Germany roadtripBali vacation
Doing this right is hard. OpenPaths samples non-uniformly in time, more points when you’re moving. So the honest thing would be to calculate dwell time from the timestamps. Also the heatmap fakery being done in TileMill is not really accurate, more of an alpha blending hack, but it does look nice. The result is not particularly scale-invariant, you need different settings for different zoom levels and different amounts of source data.
Here’s the steps I followed. Full Carto CSS below. These notes below aren’t a full cookbook, but if you sort of know TileMill already it may get you going.
Start up a TileMill project and import the OpenPaths data. Happily it detects the CSV and lat/long parameters with no trouble. Style it with simple dots and you have a map!
Add some thematic layers for orientation; I used the Natural Earth data for country boundaries, state boundaries, and the small roads file (which is sadly US only). Put the locations dots as the top layer, then I put roads, admin1, and countries below.
Switch to transparent markers. Grab the Mapnik fuzzy dot and drop it in my project directory, use that as a marker-file.
Switch to the fancy heatmap. The magic there is mostly the image-filters:colorize-alpha. Also want to multiply markers, and allow overlap.
Tweak the heatmap. Unfortunately there’s no scale-invariant way to do this, so I settled on making it look good at zoom=8. Both marker-width and marker-opacity are things you can tweak to make it look good depending on your density of location samples, zoom level, etc.
Lieux-dit are little placenames in France, for a farm or field. Les Courtes, La Botte D’Asperges, La Belle Vue, Le Télégraphe... They’re hyper-local placenames, known only to nearby residents. They do show up on road signs though, and occasionally wine labels, and they are lovely and historically evocative.
And of course they exist in Shapefile databases. Here’s some from Nantes. Sorry for the lack of basemap; I tried adding some public raster tile source to QGIS 2 but got defeated.
Update: and here’s something a bit nicer done with TileMill, with Migurski’s OSM extract thrown in as a vector basemap.
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.
I bought a digital copy of the National Geographic Magazine archives. Great data collection, horrible Adobe Air interface to access it. Fortunately the archive is basically a bunch of lightly obfuscated image files and SQLite databases. I might take a crack at making a more usable index to all the articles. To that end, some notes on the database schema I found.
There’s individual sqlite files on the DVDs and downloads, but I think they are all merged in a file called Contents/Resources/assets/db/cngcontent.sqlite3.full. I find 7977 article entries in 1416 issues for my set up to 2012, which sounds roughly the right scale. Here’s the tables in it and some notes on schema. Numbers in parentheses are how many rows are in the table.
Tables all have simple primary keys named “id”. “search_time” is a popular field, it stores the date of the issue as an integer. IE “1977 Sep” has a search_time of 19770901.
This Wired piece on Sochi maps notes that OpenStreetMap has way more map detail for the Olympic ski area than Google maps. It’s not entirely a surprise; Google’s coverage in Russia isn’t great, they’re not really into mapping ski lifts and trails, etc. Still, it’s a big world event, you’d think Google would have put some more effort into getting good data. Anyway, I did a map comparison from more sources than the Wired article. Nothing comes near OSM, but the Yandex maps aren’t bad. I did my best to make maps at the same scale centered on 43.6639, 40.3058.
Images in the gallery on this post. Some of why OSM looks so impressive is they just map a whole lot more kinds of features than other maps. That’s a mixed blessing. From worst to best, Bing and Apple have noticeably worse river and road data and are missing the railroad entirely; must be older data. Google’s maps won’t get you lost, Yandex has more local info still, and then the OSM maps have a generous amount of extra info.
Inspired by this discussion I tried to bang out a quick map of just the biggest rivers in the US in schematic form. My idea was to sort them all by length and draw them side by side, like this awesome 19th century visualization, but without straightening them first. I counted up which gnis_ids in NHDPlus had the most rows (as a proxy for river size), then made a special vector map source with just those rivers.
Sadly the resulting image (attached here) doesn’t really work. Some things are screwed up, like the Platte River in Nebraska which just kind of ends. Also you run into the question of defining what a river is; why do we call the Missouri a separate river as opposed to folding it into the MIssissippi? I could show every single watershed that has a unique drainage to the oceans, but then that’s a fanned out watershed map instead of a nice linear river map. Needs more thinking.
Boy, code rots. I tried to re-generate my vector rivers map from data. The project’s well documented, it should be easy, right! Ha.
My imports failed like this:
$ shp2pgsql -a -D -t 2d -s 4269 -W LATIN1 ./NHD/NHDPlusGB/NHDPlus16/NHDSnapshot/Hydrography/NHDFlowline.shp
Shapefile type: ArcZ
Postgis type: MULTILINESTRING[2]
Error in fread() reading object of size 1112 at offset 41917076 from .shp file
Error reading shape object 43130
I downloaded a new datafile from the source and now it works. The downloaded 7z archive is the same, I wonder if there was a problem when I extracted the data and an older version of shp2pgsql didn’t catch it? It’s not just that one file though, NHDPlusMS/NHDPlus05 is bugging out too.
Update yeah I must have had a problem extracting some of the files. Surprised my import script didn’t notice before. I wonder if earlier versions of shp2pgsql weren’t as meticulous about error reporting? Or maybe I had a clean extract last time I did a full import. The 7z archiver I have to use doesn’t handle being interrupted very well, I suspect it leaves behind incomplete files.
It’s lovely that OpenStreetMap has such a.. diverse schema. But it makes it hard to figure out how to encode stuff sometimes. I’m looking at importing a bunch of address data from other sources. What’s the right format?
The source data is diverse, but a common thing seems to be a Point mapped to a street name. Ie, the SF address database I downloaded says POINT(-122.408292 37.747785) 660 PRECITA AVE. Cool! There’s a lot of other data and ambiguity about exactly what that POINT encodes (street front? centroid of parcel? building?). But that’s a good place to start.
The OSM schema for addresses is reasonably well defined. Here are the most important tags, based on the Wiki pages for key:addr and Karlsruhe Schema
There’s additional complications for buildings with multiple addresses, and regions that don’t use city/state addressing (ie, addr:subdistrict), and interpolation, etc. Gonna punt on that and focus to what’s relevant for major US cities.
Another significant question is whether you tag the address data onto a building, or do you create a separate standalone address node. The latter approach seems necessary in the US where we don’t have building footprints for so many places. Although MapBox’s analysis is that the majority of addresses are on buildings.
Here’s a list of top address keys culled from TagInfo. I’ll note the majority of these are tags on nodes, not ways.
26M: addr:housenumber
23M: addr:street
18M: addr:city
14M: addr:postcode
13M: addr:country
There’s a second group of keys that have hundreds of thousands of entries, but many fewer than those top 5 above
I’d like to double back and see what they do in Denmark. That country has very good geocoding data and an ongoing process to sync up with the official government data.
Lots of interest in my “all rivers” map, thanks in large part to a post on kottke.org. And several requests for a poster print. I’d like to do that, would be fun to have one for myself, but before I do that I’d want to fix a few things.
The simple thing is to fix the projection, use an Albers USA. It might make sense to use Mike’s code, he’s already got the projection and a nice offline renderer instead of my goofy “screenshot the browser” approach.
The hard thing is to fix these annoying rectangular artifacts in the data. They’re visible in many places, specifically in eastern Oklahoma. I asked the NHDPlus guys and they said the NHD source data was digitized from USGS quads and that some of the quads are different than others, but they couldn’t characterize how. Looking at a zoomed view I think it’s just fewer flowlines; you can see fewer lines on the right than the left.
Taking a suggestion from Seth F I tried to only draw things with a Strahler number > 2; it softens the artifacts, but doesn’t eliminate them. Top is a whole US map, bottom is zoomed in on eastern Oklahoma. Artifacts are still visible. If some quads just have fewer flowlines that’s going to affect the Strahler calculation too. Maybe there’s some other property to filter on to remove the bias, like only rendering things with a gnis_id.
Half-finished notes, but I don’t want to lose them.
Leaflet doesn’t have a stock plugin for GeoJSON vector tiles. I believe Glen Robertson’s leaflet-tilelayer-geojson is the most complete and correct plugin, but it renders pretty slowly (several seconds for cached data). My river vector tiles tutorial includes a TileLayer.d3_geoJSON.js that renders about 10x faster, but because it uses D3 instead of Leaflet to do the GeoJSON rendering it lacks full Leaflet integration. For instance, there’s no way to bind a Leaflet popup to a LineString.
Over on the Leaflet-js mailing list I started a discussion “GeoJSON performance? River vector tile map, trying to figure out how to make Glen’s approach using Leaflet GeoJSON faster. Norbert Renner responded with some terrific experimental work that made rendering much faster, but it was sort of a one-off spike rather than a reusable improvement. Someone should spend some time with his optimizations and see if they can be ported to work in the general purpose library.
Did a bit of a goof project, mashing up a bunch of vector tile layers with crazy colors. It looks good! Also gave me a chance to rework Ziggy Jonsson’s D3+Leaflet tile renderer; TileLayer.d3_geoJson is promising. It’s certaintly a heck of a lot faster than Leaflet’s GeoJSON rendering, although there are some issues with the APIs.
I instrumented the Leaflet version of my vector tile client to show me the size of the vector tiles for the page. Chrome developer tools will do this measurement, but it’s easier to have it in console.log. All measures are uncompressed and uncached times, and for my relatively limited set of rivers (based on Strahler filtering). I intend to add more data to the vector tiles; measuring this as a baseline.
All measurements taken with a browser window about 1000 x 1000, loading about 25 tiles for the view. I slowly zoomed in on St. Louis, a fairly dense area to load.
I guess I knew that the map got lighter weight as I zoomed in, but not how much. Too bad; I’m most excited to load data in the zoomed out views. But looking at this I can move the cutoffs some and show more rivers. Update: I updated some of the thresholds around z=8 to z=13.
A large tile like 4/3/5.json gzips from 384k to 92k. A smaller tile like 8/40/97.json gzips from 29k to 7k. So let’s say GeoJSON gzips to 25% the original size; that means the biggest views will take about 500k of data on the wire to download. That’s pretty reasonable.
A whole separate question is render time. The Leaflet render is really bad and I don’t know why. The new D3 client is so fast it gives me some aspiration.
Mike Bostock took a crack at using TopoJSON to encode the NHDFlowline dataset. Just the geometry for rivers in 2 dimensions; no properties, etc. Tested just for California. All sizes are one million byte megabytes.
So for this data TopoJSON is about 1/4 - 1/5 the size of the equivalent GeoJSON. And those advantages persist through gzip. And that’s for a pathologically bad case, where there’s no shared topology along polygon boundaries. Pretty much all the savings here must be coming from the delta encoding. Neat!
Update: Mike converted the whole US. 2.5G of .shp file input, 327M of topojson output.
Note that TopoJSON quantizes. Mike used the default TopoJSON settings which I think work out to about 10,000 x 10,000 resolution, which makes the comparison to GeoJSON rounding to 3 digits about fair. Here’s a snapshot of a render of the TopoJSON that Mike gave me. It looks right.
I love this one screenshot from when I first got nice rendering implemented, showing all sorts of detailed rivers. I’ve backed way off that because it’s so much data, etc. But in filtering so much I’ve lost something.
Mike Bostock did a pure-D3 vector tile renderer, so I bashed up a river renderer. And it’s fast. So I made some screenshots where I don’t filter the data on Strahler number at all; all rivers, all the time!
The server generation time is acceptable once you rely on caching. Data sizes are pretty bad though, 27 megs a tile :-P
7/25/49: 1684 ms 640 kb 1928 features
6/13/23: 6243 ms 2308 kb 5405 features
5/6/11: 21221 ms 8841 kb 24139 features
5/7/12: 37041 ms 15146 kb 42131 features
4/3/6: 64572 ms 26870 kb 75744 features
To complement my previous timings, some more measurements of new merge strategies.
Merge by (huc8, gnis_id, strahler)
7/25/49: 275 ms 30 kb 50 features
6/13/23: 453 ms 95 kb 148 features
5/6/11: 783 ms 209 kb 238 features
5/7/12: 1048 ms 202 kb 434 features
4/3/6: 1333 ms 376 kb 783 features
Merge by (gnis_id, strahler) if gnis_id is not null,
otherwise merge by (huc8, strahler)
7/25/49: 103 ms 29 kb 45 features
6/13/23: 262 ms 91 kb 131 features
5/6/11: 543 ms 199 kb 178 features
5/7/12: 534 ms 186 kb 339 features
4/3/6: 958 ms 346 kb 600 features
That second strategy seems like the right compromise. The performance numbers are pretty good, the map is accurate, and the actual SQL queries are reasonably simple. It takes 11 minutes for me to merge all 2.7M rivers this way. The resulting table has 332,615 rows in it; that’s 322,621 rows with a gnis_id of some sort and 9994 without.
I sure wish Postgres could do this merging with a single query. The query planner seems to be doing the wrong thing and Postgres infamously has no syntax for giving hints to it. So I issue 170,000 queries, one per gnis_id, instead of doing a single insert. Here’s the query that doesn’t run in a reasonable time, combined with the explain for it. I have indices on gnis_id and strahler both, but maybe the group by on the pair confuses it.
insert into m(gnis_id, name, strahler, huc8, geometry)
select
MAX(gnis_id) as gnis_id,
MAX(name) as name,
MAX(strahler) as strahler,
MIN(huc8) as huc8,
ST_LineMerge(ST_Union(geometry)) as geometry
from rivers
group by (gnis_id, strahler);
QUERY PLAN
-------------------------------------------------------------------------------------------
Insert on m (cost=2863631.25..2944365.87 rows=124821 width=102)
-> Subquery Scan on "*SELECT*" (cost=2863631.25..2944365.87 rows=124821 width=102)
-> GroupAggregate (cost=2863631.25..2943117.66 rows=124821 width=491)
-> Sort (cost=2863631.25..2870305.66 rows=2669766 width=491)
Sort Key: (ROW(rivers.gnis_id, rivers.strahler))
-> Seq Scan on rivers (cost=0.00..206104.66 rows=2669766 width=491)
(6 rows)
Visualizing the effect of river merging. I’m coloring each line segment with a random hue. Top image is unmerged, bottom line is merged, view is at 10.00/39.0356/-122.7773.
Basic stats about the tables from NHD I’m working with
NHDFlowline
2,993,526 rows
2,993,525 distinct ComIDs
(the duplicate is ComID 17029298, Squaw Creek, and it’s not quite a duplicate row.)
2,527,374 distinct ReachCodes
181,685 distinct GNIS_IDs
70,822 distinct GNIS_names
Almost all the flowlines are < 5km in length
737,072: 0-1km
767,064: 1-2km
696,161: 2-3km
366,717: 3-4km
184,901: 4-5km
PlusFlowlineVAA
Pages 101 and following of the NHDPlusV2 User Guide are very useful in understanding how the PlusFlowlineVAA data is calculated.
2,691,346 rows (one for each flowdir == “with digitized”, according to docs)
2,691,345 distinct ComIDs (17029298 is duplicated again)
2,691,346 HydroSeqs. This number acts like a flowline ID for a lot of the VAA data, with the added advantage that the numbers are sorted upstream to downstream.
2,626,049 distinct FromNodes
1,686,246 distinct ToNodes
1,013,062 distinct LevelPathIDs
14,676 distinct TerminalPathIDs. None are null.
There are 663,408 rows with gnis_id of null and a terminalpathid of 350002977. I’m guessing these are poorly labelled tributaries for the Mississippi, but I’m not sure. It’s too many to merge!
Reachcodes
The reach code is an alternate ID for a flow that hierarchically encodes its watershed. For instance the South Yuba River has reach codes like 18020125000030, 18020125000031, etc. The first 8 characters of a reach code are separable and are either identical to or closely related to the HUC8 that the WBD datasets use. Grouping flows by HUC8 makes a lot of sense, they are geographically clustered and related. Note that reachcode shows up both in nhdflowline and plusflowlinevaa; I’m not sure if they are identical or not.
There are 2,239,489 distinct reachcodes in PlusFlowlinesVAA. The biggest is 10150005000096 which matches 100 rows.
There are 2117 distinct HUC8s in the reachcodes. The biggest HUC8 is 09030001 which has 5784 rows in it.
There are 32,439 distinct 12 character prefixes for reachcodes. The biggest one 020801110150 has 457 rows. This seems like the right size of blob for me to merge geometry on. I’m not positive it’s really correct to group by this 12 character prefix; while you see HUC12 hierarchical data in watershed boundaries, I’m not certain these reachcodes are doing the same thing. OTOH our grouping criterion can be a bit arbitrary; all we really need is some geographic locality.
Grouping criteria
So grouping by gnis_id isn’t sufficient because so many flows have that as null. How about grouping by some combination of a substring of reachcode, gnis_id, and strahler number? Here’s the sizes of various grouping options:
322,625 groups, biggest is 1153 rows
where gnis_id is not null group by (gnis_id, strahler)
this is the flawed grouping I was using. It leaves out 1.5M flows where gnis_id is null
333,405 groups, biggest is 2882 rows
group by (substring(reachcode from 1 for 8),gnis_id,strahler)
Grouping by HUC8, gnis_id, and Strahler number. Most “correct”?
454,018 groups, biggest is 391 rows
group by (substring(reachcode from 1 for 12),gnis_id,strahler)
Grouping by first 12 of reachcode, gnis_is, strahler.
Based on that analysis, the HUC8 is the right choice. There’s a reasonable number of groups, no group is too enormous, and HUC8 is a meaningful thing to group on.
So now for every single HUC8, I’m executing this insert:
insert into merged_rivers(gnis_id, name, strahler, huc8, geometry)
select
MAX(gnis_id) as gnis_id,
MAX(name) as name,
MAX(strahler),
MAX(huc8) as huc8,
ST_LineMerge(ST_Union(geometry)) as geometry
from rivers
where huc8 = %s
group by (gnis_id,strahler)
I’d rather do this as one big create table with a group by (huc8, gnis_id, strahler) but last time I tried something like that Postgres was still choking on it 18 hours later. This way I can watch it as it goes.
I think I’ve finally wrangled my vector tile data problem, the one where my server was seeing rivers as lots of little tiny line segments instead of one giant linestring. It took me a long time to work this out; merging with ST_Union() at query time was too slow, I think because the subselect that TileStache issues confuses the gist. I tried creating a merged river database in one fell swoop with a select ST_Union(geometry)... group by gnis_id but that query didn’t complete after 18 hours, Postgres wasn’t using the gnis_id index correctly. I finally wrote a Python script to merge stuff one river at a time and create a new database that way and it runs in < 4 minutes. Some data:
2,667,758 rows in the rivers database. Each one has a simple LineString for geometry.
1,086,512 rows with a gnis_id. Another 1,581,246 where gnis_id is null. Those nulls seem to be causing a problem, see below. (There’s 1,899,204 gnis_id nulls in the source nhdflowline database; I must have tossed some when joining on comid to make the rivers table in the first place.)
322,621 rows in the merged database (“rivers2”, for this discussion). Each has a MultiLineString for the geometry, just ST_Union().
178,906 unique rivers in the dataset (identified by gnis_id). I don’t merge all this way in rivers2 because I want to keep them separated by Strahler number. Ie: the Missisippis has 7 rows in rivers2, the little tiny part at Strahler=2, the bigger part at Strahler=3, ... all the way to Strahler=8 at the Gulf.
I later improved on things by making a rivers3, which is an ST_LineMerge(ST_Union(geometry)); that stitches together LineStrings where possible. Adds about 10% overhead to the table building, but significantly better results on serving.
One failure of this approach is gnis_id is sometimes null. Right now I’m just throwing those geometries away in the merging process and the result is broken lines, bits of rivers are missing. Visual inspection suggests its in places where gnis_id is null, and there’s a lot of those. I took a shot at a rivers4 where I just copied all those nulls in. It looks correct, which is a virtue, but we’re back to bloated data and query times. Need to dig more into NHDPlus and figure out why gnis_id is null in so many places, what to do about it.
Old way (rivers)
7/25/49: 577 ms 258 kb 1715 features
6/13/23: 2281 ms 1048 kb 6911 features
5/6/11: 5421 ms 2549 kb 16953 features
5/7/12: 6457 ms 2659 kb 17781 features
4/3/6: 10359 ms 4855 kb 32439 features
New way (rivers2, with ST_Union)
7/25/49: 436 ms 58 kb 25 features
6/13/23: 874 ms 243 kb 90 features
5/6/11: 1648 ms 538 kb 81 features
5/7/12: 2236 ms 649 kb 162 features
4/3/6: 3435 ms 1175 kb 275 features
Newer way (rivers3, with ST_LineMerge(ST_Union()))
7/25/49: 48 ms 9 kb 25 features
6/13/23: 86 ms 23 kb 90 features
5/6/11: 89 ms 21 kb 81 features
5/7/12: 162 ms 41 kb 162 features
4/3/6: 216 ms 53 kb 275 features
Newerer way (rivers3, with nulls included)
7/25/49: 244 ms 98 kb 613 features
6/13/23: 814 ms 347 kb 2223 features
5/6/11: 2017 ms 946 kb 6188 features
5/7/12: 1648 ms 691 kb 4499 features
4/3/6: 2934 ms 1316 kb 8664 features
My vector river tiles app is unacceptably slow when drawing maps way out, like at zoom=6. I know what the problem is; there’s just too many rivers and geometry. But I’d hoped that it would magically work anyway. Some notes on where the time is going.
First, a testing setup. This is remarkably awkward; there have never been good off the shelf tools for measuring database slowness :-( After a failed attempt to make TileStache use a LoggingCursor what I came up with is:
gunicorn configured for a single synchronous worker. It’s unrealistic, but much easier to follow.
TileStache configured to debug level INFO. It emits nice lines like
INFO:root:TileStache.getTile() riverst/6/13/23.json via layer.render() in 2.090
Basic client test; load a map and when it gets slow, look in the TileStache logs for specific tiles that are taking a long time.
Postgres configured with log_duration=on and log_statement=all. This gives you helpful log lines like LOG: statement: SELECT ....
LOG: duration: 621.962 ms
By syncing these all up I know that the tile z=6 13/23 is taking 2.09s for TileStache to create, 620ms of which is the database. And the GeoJSON output is a megabyte. That’s already very useful data; I had no idea TileStache itself was doing so much work.
Now I can take that query and look at it. For instance, that one tile returns 6911 rows! This is the NHD schema biting me in the ass; rivers are broken up into a lot of little points. The Cheyenne River on that tile, for instance, is returning 448 different rows with little LineStrings of 2-30 points each. Way too much detail for such a broad overview tile.
Some basic timings for the slowest query I could find at various zoom levels.
Looking at this data, I’m thinking the bigger problem may really be the GeoJSON size. The tile generation time is awful but then again there’s only a few thousand tiles at zoom 7-0, can just cache them all. But there’s no love in sending all those tiles to a web browser client! The chopped up geometry is a problem for the GeoJSON too; each little LineString gets encoded as a separate feature with its own properties, so the string “Cheyenne River” is in the GeoJSON tile 448 times. Really need to fix that.
Here’s the query TileStache issues for 4/3/6 as well as the “explain analyze” output:
SELECT q.*,
ST_AsBinary(ST_Transform(ST_Intersection(ST_Simplify(q.geometry, 9783.94), ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913)), 4326)) AS geometry
FROM (
select geometry, name as n, strahler as s from rivers where strahler >= 6
) AS q
WHERE ST_IsValid(q.geometry)
AND q.geometry && ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913)
AND ST_Intersects(q.geometry, ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-12523442.71, 2504688.54), ST_MakePoint(-10018754.17, 5009377.09)), 900913))
Bitmap Heap Scan on rivers (cost=9362.71..41858.70 rows=943 width=478) (actual time=176.078..2661.831 rows=32439 loops=1)
Recheck Cond: ((strahler >= 6) AND (geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
Rows Removed by Index Recheck: 65107
Filter: (st_isvalid(geometry) AND _st_intersects(geometry, '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
-> BitmapAnd (cost=9362.71..9362.71 rows=8487 width=0) (actual time=175.357..175.357 rows=0 loops=1)
-> Bitmap Index Scan on rivers_strahler_idx (cost=0.00..1904.82 rows=102971 width=0) (actual time=10.056..10.056 rows=102825 loops=1)
Index Cond: (strahler >= 6)
-> Bitmap Index Scan on rivers_geometry_gist (cost=0.00..7457.17 rows=217628 width=0) (actual time=163.464..163.464 rows=754699 loops=1)
Index Cond: ((geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry) AND (geometry && '010300002031BF0D000100000005000000EC51B856F6E267C152B81E45F81B4341EC51B856F6E267C15C8FC245F81B5341D7A37045F81B63C15C8FC245F81B5341D7A37045F81B63C152B81E45F81B4341EC51B856F6E267C152B81E45F81B4341'::geometry))
Total runtime: 2666.323 ms
Update: I played around with merging geometries in the database by grouping on gnis_id. It’s got some problems, I think I broke the gist (every query is taking 35 seconds at any zoom level!) But the approach has some promise. At least it’s making for smaller outputs; 28k vs 264k for 7/25/49, 88k vs 1073k for 6/13/23.
explain analyze SELECT q.*,
ST_AsBinary(ST_Transform(ST_Intersection(ST_Simplify(q.geometry, 2445.98), ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913)), 4326)) AS geometry
FROM (
select ST_LineMerge(ST_Union(geometry)) as geometry, max(name) as n, max(strahler) as s from r where strahler >= 5 group by (gnis_id, strahler)
) AS q
WHERE ST_IsValid(q.geometry)
AND q.geometry && ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913)
AND ST_Intersects(q.geometry, ST_SetSRID(ST_MakeBox2D(ST_MakePoint(-11897270.58, 5009377.09), ST_MakePoint(-11271098.44, 5635549.22)), 900913))
Subquery Scan on q (cost=354441.41..380026.21 rows=10258 width=72) (actual time=2563.823..36912.769 rows=93 loops=1)
-> GroupAggregate (cost=354441.41..377282.19 rows=10258 width=497) (actual time=2562.281..36041.899 rows=93 loops=1)
Filter: (st_isvalid(st_linemerge(st_union(r.geometry))) AND (st_linemerge(st_union(r.geometry)) && '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry) AND (st_linemerge(st_union(r.geometry)) && '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry) AND _st_intersects(st_linemerge(st_union(r.geometry)), '010300002031BF0D000100000005000000295C8FD236B166C15C8FC245F81B5341295C8FD236B166C1E17A144E777F5541E17A144E777F65C1E17A144E777F5541E17A144E777F65C15C8FC245F81B5341295C8FD236B166C15C8FC245F81B5341'::geometry))
Rows Removed by Filter: 3599
-> Sort (cost=354441.41..354953.32 rows=204764 width=497) (actual time=2009.868..2244.670 rows=204904 loops=1)
Sort Key: (ROW(r.gnis_id, r.strahler))
Sort Method: external merge Disk: 73896kB
-> Bitmap Heap Scan on r (cost=3835.46..197798.53 rows=204764 width=497) (actual time=31.229..642.727 rows=204904 loops=1)
Recheck Cond: (strahler >= 5)
Rows Removed by Index Recheck: 1371179
I made the mistake of doing a bunch of testing of TileStache with the simple Python CGIHTTPServer. It’s a great little test apparatus, but it’s single threaded. Also it’s slow by itself.
CGIHTTPServer: 750ms to load a single tile, 10,000ms to load a whole map with 24 or so tiles
Gunicorn with 4 workers (sync): 650ms to load a single file, 2154ms to load a whole map.
Some comparisons on Gunicorn settings to load a map with 24 tiles.
1 worker, default sync worker: 4800ms
2 workers, default sync worker: 2500ms
4 workers, default sync worker: 2300ms
24 workers, default sync worker: 1700ms
Interestingly the gevent worker seems slower, also more variable. OTOH it’s necessary if you’re serving GUnicorn direct to the web, without a proxy in front.
The backend server is mostly waiting on IO to Postgres, it’s no surprise doing that in parallel will be better. All on a single 4 core 2012 iMac with some SSD-backed storage. I should add I’m doing this all without benefit of any caching, so it’s all kind of fake.
Repeat after me: I will dump my databases before upgrading PostgreSQL or PostGIS. I will dump my databases before upgrading PostgreSQL or PostGIS. I will dump my databases before upgrading PostgreSQL or PostGIS.
I got fed up with the 2 year old versions of GIS software in Ubuntu 12.04 so I upgraded to versions from the awesome Ubuntu GIS PPAs. However after upgrading PostGIS any spatial query gave me the error
ERROR: could not access file “$libdir/postgis-2.1”: No such file or directory
No idea why that says “2.1” when I installed PostGIS 2.0.1 (2.0.1-2~precise3), but there it is. Googling around I realized this is a symptom of not reinstalling the PostGIS functions in the database. There’s a variety of confusing database upgrade options, and the Debian packages are very clear about not injecting any SQL for you “for safety”.
However, there is a better way! Starting with Postgres 9.1 and PostGIS 2.0, PostGIS can be installed as a simple database extension. No more futzing with template databases on creation or importing lots of .sql files in a new database. All you need to do to spatialize a new database is
I’m not sure you can use these commands to rescue an old database that didn’t survive an upgrade, but it works great with new databases. IIRC there’s even an upgrade path for extensions. I dropped my old template_postgis2 just so I never get confused again.
Some notes for a quick project I did with Mike Migurski’s help, making a map of California rivers using vector tiles. The river data is from NHDPlus, about 180 megs of shapefile, imported into PostGIS. It’s served as manageably small GeoJSON tiles via a TileStache VecTiles provider which slices up the data like raster map tiles. Rendered for now in Polymaps. Works well!
TileStache is already smart about simplifying the geometries it returns to roughly pixel precision, depending on tile zoom level. It’s really pretty great. But I also want to serve fewer rivers at larger scales, only show the important rivers. Need a classifier. I don’t think the propery I need is in NHDFlowlines but may be in NHDPlusAttributes, more thoughts in this GIS tutorial. Seth F advises “PlusFlowlineVAA has value-added attributes that can be joined on ComId. streamorder is the column you’re looking for. It’s the Strahler number (http://en.wikipedia.org/wiki/Strahler_number) for a given section of river.”
I ran into some problems with queries from GDAL not working with PostGIS 2.0. Used to be you could just call functions like GetSRID() etc, now you have to do ST_GetSRID(). The old GDAL 1.7 on my Debian box doesn’t know that yet and the Vector provider in TileStache relies on it, so it doesn’t work. VecTiles generates its own queries and Mike was kind enough to patch his code to use the ST_ names.
The TileStache VecTiles code only works with a spherical mercator projection, so I had to do this in PostGIS to add a reprojected column:
I don’t work with shapefiles and PostGIS enough to remember how to import a shapefile into a table. I want to import the NHDPlus dataset for rivers. There’s lots of ways to do this, here’s what’s working now in a plodding, step by step way.
createdb -T template_postgis2 nhd
shp2pgsql -W LATIN1 NHDFlowline.shp >| /tmp/o
psql nhd < /tmp/o
echo ‘CREATE INDEX “nhdflowline_geom_gist” ON “nhdflowline” USING GIST (“geom”);’ | psql nhd
This can probably be done on one line with shp2pgsql -I foo.shp | psql nhd
Getting fancier on the import (and setting the SRID to 4269):
Related: shp2pgsql won’t look at the .prj file to figure out the projection. Figuring out a projection is still way too hard and Prj2EPSG.org failed me. This StackOverflow question and this one have a neat trick; use osgeo.osr.SpatialReference().AutoIdentifyEPSG() to guess the projection.
Update: Seth F has a nice shell script for importing a lot of useful NHD data and creating important indices.
Trying to work with the data files for this awesome Volcano map from USGS. They helpfully published their GIS data for free download; unhelpfully it’s in ESRI’s proprietary E00 format. Some notes.
An E00 file is a container for geography data with annotations like centroids, labels, etc. The volcano files also contain auxiliary .avl and .lyr files that seem to be graphical legend definitions, etc.
The format is mostly straightforward ASCII and somewhat documented. It’s a container format; inside it are geometries and other properties. The part I’m really interested in is the PAT section, which seems to have labels and auxilliary data for the geometries defined in the ARC section. I could probably fake out a join of my own from the ARCs to the PAT data without too much coding. To complicate things I think the geometries are line boundaries between polygons, like TopoJSON, and not the polygons themselves..
QGIS can load an E00 file, but all it seems to do is grab the geometry as LineStrings. It loses all the metadata. It’s also super slow. Way faster loading the ARC shapefile that ogr2ogr generated. I forget, do shapefiles contain spatial indices by default?
Seth F wrote to tell me about avce00, a program that converts binary coverages to ASCII E00 and back. What’s a coverage? That’s ESRI’s name for “a bunch of spatial data with auxiliary data”, ie the bundle in the E00 file. The main thing it seems to do is covert between binary and ASCII E00; I don’t need it for the volcano data.
GDAL ogr2ogr has some E00 support. A simple ogr2ogr is doing a game job of creating multiple shapefiles with my data. It is terribly slow, 3+ hours on my 30 meg input file. But it does seem to convert the data. There’s a shapefile named ARC that contains the boundary LineStrings and a shapefile named PAL that doesn’t have any geometry in it, but contains the auxiliary data I care about from the PAT section.
Anyway, the ogr2ogr converted shapefile seems reasonable to work with. The properties for the main geometry table named ARC includes integer fields named FNODE_, TNODE_, LPOLY_, RPOLY_, BIMGEO_FN, BIMGEO___1 (copied? to UserId), and LINE-TYPE. There’s 21,563 rows in the properties table, and roughly 6745 unique LPOLY_ ids and an unknown but < 16578 unique BIMPGEO__1.
Meanwhile, the PAL table has 6744 rows with the fields I really care about: YEAR1 and YEAR2 as well as LABEL. It also has BIMPGEO_FN, which looks to be a unique ascending integer 1..6746 and a BIMPGEO__1 field, 0..6980. I’m betting one of those is a key I can join to LPOLY_ on the ARC table to associate the years and label to the geometry.
I tend to forget that ESRI shapefiles are more like databases than just bags of geometry. ogrinfo can extract features.
ogrinfo -geom=no -sql "select HUC_12,HU_10_NAME,HU_12_Name from WBD_Subwatershed" WBD_Subwatershed.shp
unfortunately the output is some terrible text format.
OGRFeature(WBD_Subwatershed):3
HUC_12 (String) = 180703030303
HU_10_NAME (String) = Lower San Luis Rey River
HU_12_Name (String) = Pilgrim Creek
However it turns out using GDAL/OGR’s bindings to Python is relatively straightforward, even if the API is basically a straight-up rip of the C API. Decent tutorial is here.
import ogr
shapefile = ogr.Open("NHDPlusCA/NHDPlus18/WBDSnapshot/WBD/WBD_Subwatershed.shp")
layer = shapefile.GetLayerByName("WBD_Subwatershed")
for feature in layer:
featureDefinition = layer.GetLayerDefn()
for i in range(featureDefinition.GetFieldCount()):
fieldDefinition = featureDefinition.GetFieldDefn(i)
print fieldDefinition.GetName(),
print "%s" % feature.GetFieldAsString(i)
Who knew? ESRI has some very nice image tiles readily usable in Javascript maps. I particularly like the World Shaded Relief map; just hill shades and water, nothing else. Shame about the pink cast, but it mostly works for me. The terms of service are very permissive too.
I played more with the California watershed boundary data and TopoJSON. Two nice treatments, online at least temporarily. A full-state static map in D3 with some mild interaction letting you change the depth of HUC codes used in coloring. And a zoomable map written with Leaflet that while HUC colored, emphasizes watershed boundary details over the hierarchical HUCs.
The Leaflet implementation went pretty well. The one thing that tripped me up is my watershed boundaries are stored as bunch of Geometry objects in a GeometryCollection, instead of Feature objects in a FeatureCollection. Leaflet’s GeoJSON support does nice things with FeatureCollections, letting you change the style and bind a popup for each Feature. It doesn’t seem to do that with GeometryCollections. I worked around it by just iterating through the GeometryCollection and adding each Geometry manually. But I wonder if TopoJSON should be emitting FeatureCollections instead? ogr2ogr on my source .SHP data emitted a FeatureCollection, but topojson generated a topology with an embedded GeometryCollection.
I had to regenerate the TopoJSON for the zoomable map with less simplification. 2.2 MB vs 1.4 MB, and it looks good at reasonable zoom scales. I realized too late I really should have changed the quantization from 10,000 to 100,000; but at this simplification level I can get away with it.
So that’s the result. It’s OK and a useful tool for exploring watersheds, but it’s not awesome. The file size and render times are awfully big. And the presentation is clumsy, I should do more.
I played around with Mike Bostock’s TopoJSON today, a file format + Javascript library for efficiently encoding maps. It basically does the same thing as geojson, but gets amazing compression in part by identifying common line segments between polygons and only encoding them once (ie: draw the border just once) and in part by quantizing and simplifying all the data. It’s quite clever!
My test data is the Watershed Boundaries from NHDPlusV2; the California-only NHDPlusV21_CA_18_WBDSnapshot_01.7z (89MB) and the national NHDPlusV21_NationalData_WBDSnapshot_Shapefile_01.7z (1.7GB).
Converting
Converting the smaller file to TopoJSON was a snap, just
The flags are to add some GeoJSON properties to the resulting data file.
Simplifying
Taking the default arguments, TopoJSON reduced my 89MB SHP file to a 9.3MB TopoJSON file. Not bad, particularly since the straight GeoJSON is 257MB. A lot of compression thanks to shared boundaries. But also quantization; by default the topojson tool quantizes data to 10,000 values; I’m not sure but I think that means “it’ll look right if your map isn’t more than 5000 pixels wide”.
But topojson doesn’t do any simplification by default. What if we add the -s flag to simplify? Here’s the file size for variants of the -s parameter (in steradians):
To my eye, the 1.4 MB 0.00000001 version looks about right, at least on my 800x800 map. I’m not surprised simplifying to a gross accuracy like 0.001 doesn’t add much; the objects themselves are pretty small. Not sure why it tops out at 5.8 MB or almost half the size of no simplification; maybe the source data has some really silly little details?
Querying the JSON
Quick diversion; I wanted to query my JSON object, to see what the properties and stuff inside it were. Someone’s finally built a decent “grep for JSON”, jq, the “keys” function is particularly useful for exploring a JSON file. Some quicky bits:
# get all HUCs:
jq '.objects.WBD_Subwatershed.geometries[].id'
# get all properties:
jq '.objects.WBD_Subwatershed.geometries[0].properties | keys'
Big data
I foolishly spent half my afternoon trying to convert that 1.6 GB file for the whole country. TopoJSON is memory-hungry; the optimization it’s doing is global so it really wants to read everything in to RAM. Long story short, the main thing I learned is that just like a Java VM the V8 VM has a fixed memory pool that’s like 1 GB or something by default. The magic flag to node is ” --max-old-space-size”. If I set it to 5000 (MB) then the whole process seemed to want to take 10 GB and made my 8GB machine thrash. Unfortunately smaller numbers like 4000 or 3500 resulted in an out-of-memory error. Mike guesses I’d need 16 gigs of RAM to do the conversion. All sort of silly anyway; I’m not sure what I’d do with the giant resulting file.
On the way I learned a lot of ugly things about Mac memory management:
Activity Monitor reports an “inactive memory” number that’s complete nonsense. It’s supposed to be RAM available for other processes but it sat at 3GB while my user process was thrashing the swap. So either the VM is not letting me use memory, or else it’s not really inactive afterall. The “purge” command doesn’t really help here, btw.
The page ins / page outs numbers on Activity Monitor are hugely helpful. When it’s paging in at 30 MB/s (hard drive rate) you know something is bad.
The %CPU number is also useful. When thrashing my topojson process dropped to 25% CPU (from 100).
If you double click on a process you get some detailed data. The “memory” page is confusing; I kept ignoring the “virtual memory size” of the process when that turns out to be the most relevant number. That was the 10 GB that resulted in thrashing. The Real Memory Size never got over 6 GB despite having 8 GB of RAM; guess MacOS overhead is 2GB now.
The geniuses at apple renamed “vmstat” to “vm_stat” and made it work differently. But it’s somewhat adequate.
Drawing Maps
Haven’t gotten very far for actually making maps yet. I followed Mike’s Let’s Make a Map tutorial and got a maplike something up pretty quickly. Counties in red, watersheds in black outline. My main goal is to add some color interaction around the hierarchical HUC coding.
The new Javascript OSM editor iD is working on live data now. So I made an edit, adding a pond I know is there by tracing it on Bing. Works pretty well, it’s an impressive JS app. Interactivity is not great, need 30fps+ responsive user feedback to really feel right. But it’s an early alpha, I’m sure they’ll get there.
The CSS looks home rolled other than a stock reset. Here’s the third party JS libraries they use:
Notice what’s missing? A typical slippy map library like Leaflet or OpenLayers. He’s using D3 instead. I hadn’t realized how far along d3.geo.tile has come. Works pretty well on iOS too!
Twitter published user archives, hooray! I cargo culted some code together off of Mike’s Walmart map to show a little histogram of where I tweet. Two maps with different projections and different visualization of magnitude (size vs color)
Some things I learned:
Hexbins can be brittle. If I change the scale of the map or the hexes just a bit the qualitative shape of the connected objects changes radically.
Scaling and centering a projection to a dataset is a little tricky. d3.geo.projection() has you doing the scaling and translation in screen coordinates by default, need to do it in geo coordinates to make more sense. (Mike says to use the center() method.)
D3 projections are fun! The second projection is a kavrayskiy7, whatever the hell that means, borrowed from this example.
Playing around with a vector river map of California. Some notes.
Datasets
The Natural Earth major river dataset is pretty good. Not quite detailed enough for the Dreamflows scale map. Also everything looks to be about 2000m north of the natural boundaries defined by counties, other river datasets, etc. Maybe I screwed up a projection?
After a 3 day delay the NHD finally gave me back a shapefile with detailed flowlines for Nevada County. It’s very detailed data but it still has fewer small creeks on it than Google Maps or Stamen Terrain Maps. It might just be seasonal data, or maybe someone has a more detailed set. I need to explore NHDPlus.
Nick was kind enough to give me a shapefile of major rivers in California; 5 meg shapefile, 648 objects. It looks like about the right level of detail for the Dreamflows map, I’m working with it now although I want to circle back to NHD or some other primary source.
This converts the projection to EPSG:4326, the GeoJSON default. It contains ridiculously precise floating point numbers so could use some rounding with LilJSON or the like.
-simplify is useful to minimize the detail in the geometry. The tolerance parameter seems to be in the source CRS, so with this dataset in meters I’m trying “-simplify 100” or the like. 200 meters rounded to 4 digits of lat/lon seems like a good compromise; the rivers aren’t too janky at the scales I care about.
The resulting GeoJSON file is 200k compressed. Sure takes a long time for Leaflet to draw. For this kind of application I really want tiled, variable resolution vector data. Polymaps supported that years ago but it was complicated and underutilized. I wonder if anyone’s done it in Leaflet? May be overkill if I can make a Dreamflows-specific vector dataset.
Pictures
Here’s a QGIS image of a bunch of different data sources showing northwestern Nevada County. Pink dot is my house, center of the map is Deer Creek running west of Nevada City down to the Yuba. This data set is missing local reservoirs and ponds. Thick green line is Natural earth data, thick blue line is Nick’s rivers, and spidery blue lines are the N HD detailed data. Black line is the county border.
And here’s a snapshot of the Dreamflows map I made a few days back with vector rivers overlaid. I like how it highlights the river flows to put the gauge dots in context. But I need a better data source; this one has many rivers that aren’t relevant to the map, and other rivers like Cache Creek and Antelope Creek are missing. I probably should cherry-pick just the rivers that I have gauge data for.
For the Nevada City Hackathon last weekend I built a map of river flows. Just in time for the torrential rains! All of the data comes from DreamFlows, a kayaker site. They collect real time river flow data from other sites, then process it and present it in a handy table format showing where the rivers are running high for good kayaking. Great site. What I couldn’t find at DreamFlows was a map of all the gauges, showing a picture of the whole state. So I made one!
DreamFlows is kind enough to publish a CSV file of the aggregated real time data. My code takes that CSV data and draws it on the map via Leaflet. There’s a bit of extra work in geocoding the station IDs; I had to scrape station locations out of the site pages and put them in a JSON database. As is my way these days all my code runs client side; the only code on my server is a tiny shim working around Same Origin policy for the CSV file.
The resulting map isn’t bad for just a few hours work, but there’s a lot of things I’d like to do better. Some ideas:
Get data directly from the sources atCDEC and USGS. Mostly for historical data; DreamFlows only publishes current readings. Nick Santos at the Hackathon just wrote a USGS access library which could come in handy.
Visualize flows on the map. Right now I’m just drawing dots colored by DreamFlows’ classification. I’d like a more dynamic view, one that conveys the volume of water moving at each site more viscerally. I’m not sure whether to try to put a little historical graph right in the map, or maybe go for an animated presentation so you can watch flows come and go like a little movie.
Highlight rivers on the map. It’s hard to follow the courses of rivers on the terrain map I’m using. My thought is to produce a GeoJSON file of river flowlines and draw it with vectors on top of the map to highlight rivers. NHD is the canonical source for river map data in the US but it’s a hard site to work with. Nick pointed me to NHD Plus which augments the NHD data and makes it easier to work with.
Update: Chris at DreamFlows was kind enough to point out that his site has a Google Map like this too. It’s available under the Custom flows options and requires a login and a little setup, but you can end up with a dots-on-a-map almost exactly like mine.
Mike Bostock has published topojson, a clever variant of GeoJSON that more efficiently encodes toplogies. For a map of US counties, for instance, the GeoJSON approach is a bunch of LineStrings or Polygons that define each state boundary. There’s a lot of redundant line segments; TopoJSON eliminates those by encoding the line segments separately and then referencing them to define each state boundary. Also TopoJSON uses a relative integer representation instead of absolute floating point geocoordinates, greatly reducing size.
But is it as small as possible? There’s a lot of pairs of small integers like [-1,0],[1,-20],[-14,10],[-27,-9]; roughly 8 bytes for what could fit in 2. I took a quick crack at using msgpack to encode the JSON for us-counties more efficiently, this is what I learned:
Msgpack is about half the size of JSON, but after gzip that difference goes away. That’s what I found last time I looked at msgpack, too.
Some custom encoding could make the TopoJSON format smaller still, but I’m not convinced that after gzip it will make much difference. Probably not worth the complexity. The one thing I’d consider is recoding the list of pairs of integers just as a list of integers, so instead of [[-1,0],[1,-20],[-14,10],[-27,-9]] you have [-1,0,1,-20,-14,10,-27,-9]. That removes 2 bytes per pair, although after gzip that may be negligible. (update: Mike tried it. 552K (vs. 656K) for uncompressed 164K (vs. 172K) for compressed)
Nathaniel Kelso has an awesome post about how to make PostGIS more friendly for users. I mostly agree with his points, it’s a friendly todo list, although there’s always the question of who has time to do the work. Some specific thoughts (I can’t figure out how to comment on his blog):
1 Installation: I’d love updated Debian/Ubuntu packages. But it’s a lot of packaging work, I could see why PostGIS would rather defer to some third party to do the packaging. But someone’s got to do it! Upgrades are particularly hard to get right; Postgres and PostGIS mostly leave it up to users to figure out how to do upgrades right now.
2.1 imports: is ogr2ogr any better than shp2pgsql in general?
2.1g importing shapefiles: yes, absolutely, automatic inference of SRID from PRJ files. Is that a solved technical problem though, or is it arbitrarily difficult?
The #1 thing I want to make PostGIS easier is some better graphical query tool / front end to explore geometry queries. I’m used to being able to experiment with SQL in something like pgAdmin to build up my complex queries, but you can’t do that meaningfully with spatial data. I’d love a geo-aware SQL tool, one that draws geometries and stuff. I use QGIS like this a little bit but the UI for refining queries is awful. TileMill is a little better for query tinkering, but still awkward. Wouldn’t it be awesome if Induction were geo-aware, maybe using GeoJSON as a lingua franca?
Shapefiles have a .prj file which is a text description of the projection used in the shape. For some reason shp2pgsql ignores this and inserts things with the SRID 0 unless you explicitly set one with a -s flag. Maybe it’s because it’s hard to reverse the text description in the .prj and turn it into a simple SRID that PostGIS already knows about?
Update: yeah, it is hard to do the mapping of .prj -> EPSG. The .prj may even describe some weird projection not in EPSG. But for many cases it should work. The website prj2epsg.org does a best effort match.
Anyway, trying to add Mike’s metro extracts coastline to my SFO Bravo airspace database, for another lasercut with a map superimposed. Sort of have it working, but need to clean it up to remove the annoying vertical and horizontal lines: shp2pgsql -s 900913 sf-bay-area.shp | psql faa
It’s big! 9″ diameter, 2″ thick. It’s just a little too big for me, hard to comfortably hold in the hand. I think I could use the P2 Ponoko sheets and get a 6″ diameter object that felt better in the hand. OTOH that screws up the scale even more; the actual airspace has a 30:1 ratio (60nm diameter, 10,000′ thickness). Maybe I could drop to thinner sheets too, 3mm instead of 4.5mm
I don’t love the material (4.5mm light blue acrylic). The translucency is visually distracting and hard to photograph. It’s reflective and a lot of live light inside. And the mirror surface shows fingerprints and smudges from the paper backing glue like you wouldn’t believe. I’m wondering if this wouldn’t work better as a flat white solid material. Or maybe wood, or even metal.
After I took the photos I realized I kinda prefer it upside down. Ie: put the surface ring on the top of the object, the 10,000′ ring at the bottom. You can’t just flip it over, you half to flip each sheet (mirror image) to keep east/west correct. But looking top down all you see is one big sheet, no detail. You have to look from the ground to see the detail.
Assembly is a little challenging, particularly the 4000′ ring which has almost no detail, just symmetry. If I’m making these as kits I should engrave some notes on each disc. That’d work even better if it’s opaque material.
The square spindle hole in the middle with a lasercut matchstick to hold it together doesn’t work well. Has about ±5° of wiggle, either from imprecision in the hole or flex in the stick itself. Really needs to be glued together, I suspect, need to read up on that.
The actual cut lines are great. Really worked out well. I don’t think I need to do anything more with the geometry, really.
I should engrave a map on the top of the biggest disc. Coastline + airports + major roads, maybe. It’d be neat to engrave some map stuff on the bottom of the discs, too, but it’s a bit tricky with the overlaps.
Took about 45 minutes to put together, most of that time peeling the backing off the discs. Would take longer if I cleaned each disc properly and even longer if they’re glued.
Ken suggested making a shape that’s more like a bowl; just the hull of the object. That’d be neat because you could see inside it, too. 3d printing would be the natural way to do that.
I got back my second Ponoko cut of my walks. It came out pretty well. The etching of my most popular tracks came through really nicely; can’t see it in the photo but the burnt area in the middle is also quite deep. Could be deeper actually. And I love the ragged outline of the shape, it’s quite nice.
What didn’t work well is the burning of the wood on the edges of the cut, like around the bottom edge. That’s a common enough problem when lasercutting wood and in some cases it can be quite pretty. But here its uneven and blotchy and distracts from the fine line cuts. I suspect there’s no way to control this through Ponoko and I’d be better served with some other material.
There’s a bunch of passive location trackers out there. Mobile phone clients that watch your location all the time and upload reports of where you are every 15 minutes, hour, whatever. Three I’ve tried are OpenPaths, Google Latitude, and Geoloqi. Of the three I like OpenPaths the best. It’s by Jer Thorp, a very smart information visualization guy. It’s simple and does its thing well and nothing more. And it has the right goals and attitude. Google Latitude is opaque, corporate, and seemingly abandoned; it also has a terrible UI that only lets you get 30 days of data at a time. Geoloqi is nice but the tracker is more of a demo for their very capable platform. So OpenPaths is the one I’ll keep around.
That’s about three months of data, my travels around California. I like how the data shows all the different roads I’ve drive on my trips out of SF, particularly highway 12 across to Lodi. The couple of points east of Concord make me laugh, that’s when I was in Ken’s airplane and forgot to turn off my cell phone.
I’m not sure what I will end up doing with this data, but I intend to keep collecting it.
I always forget about the GeoNames web services. They’re awesome, a set of very simple REST like services for geodata. They also distribute a database. I don’t really understand the business, but they’ve been around some six years and seem to do their thing right. I used them for my WikiHere hack a few years ago and am about to use their elevation service for another quick hack.
They publish things right. Data is available in XML or JSON or JSONP formats and they set the CORS header so you can do cross-site javascript with no drama. I was originally going to use Google’s elevation service but they have no cross-site solution, not to mention my use would be unlicensed. So screw em.
Geonames asks for you to register and pass a user name on requests, they have a credit limit on requests. It’s 30,000 credits / day for free, most requests are a single credit, goes from 0.1 to 4 credits / request.
Their primary value add seems to be a broad database of place names, postal codes, etc. International. I don’t know how it compares to competing offerings or indeed if there even are any competitors. They also have time zones, wikipedia, some OSM data searches, etc. I’m using the elevation service, they have three to choose from: GTOPO30, SRTM3, and Aster. Too bad there’s no NED 1/9 for the US, but that’s a lot of data.
I finished up my lasercutting project, a model of SFO Bravo airspace. It’s a stack of 11 roughly circular objects, one every 1000′, that when stacked should be SFO bravo. It was a total pain finishing this out from the rough SVGs, but I think I’m there. It will be about 7in in diameter and 2in thick when assembled.
I ended up doing most of the finishing work in Inkscape. I never could get the SVG objects to scale correctly; the SVG viewpoint and scaling model is really confusing. And after calling ST_Union on the shapes I still had some interior lines I had to delete manually. But I got it close enough and could then paste all 11 objects into the Inkscape template, scale and style afterwards.
I got clever and cut a square hole in the middle of the airspace to insert a spindle. Hard to find that position, btw, it’s not really the center of any of the objects. It’s implied by the radii of the circles. Anyway I figured it out (it’s the VOR location, as expected) and added a rectangle to cut. I think I managed to make the holes 4.5mm wide, the width of the material I’m using, and even cut a 4.5mm long rod elsewhere on the sheet to use as the spindle. But it’s hard to get precise measurements out of Inkscape; it seems to be using the line width as part of the size of the object or something. And I’m in the habit of making the lines 1mm thick while editing so I can see them, then rescaling to 0.01mm for the final cut, which seems to throw off all the sizes. Oh well, if the spindle’s not perfect it’s OK.
It’ll cost of $37 + shipping in blue acrylic. Amazing how much cost depends on thickness. 4.5mm acrylic = $37, whereas 3.0mm is $20 and 5.6mm is $51. Most of that is laser time.
Another Ponoko project, making a 3d model of San Francisco’s Bravo airspace. It’s a bunch of roughly circular slices, should be great cutting a disc every 500′ or 1000′ to the outlines of the bravo. Some first steps to getting there, from raw data to basic (not finished) SVG files.
1. Download the FADDS database to get the FAA’s shapefiles of airspace. It contains some shapefiles for airspace.
2. Identify the coordinate reference system because shp2pgsql isn’t smart enough to guess. Class_b.prj says:
A quick lookup lets me know this is NAD83, EPSG:4269. That’s what I would have guessed, it’s quite close to WGS84, the GPS reference everyone sane uses. US government prefers NAD83 for some complex historical reason.
4. Try loading the data into QGIS and see if it looks right. This is where projections start to matter. The Project Properties dialog lets you reproject the data on rendering; you have to check “Enable on the fly CRS transformation”. The SF bravo looks wrong when projected to WGS 84 (EPSG: 4326), too squashed. They should look like circles, using some projection local to San Francisco. There’s a few NAD 83 / California Albers projections that do pretty well, like EPSG: 3310.
Even better is grab Aeronav’s GeoTIFF for San Francisco and see what they use; pilots expect the airspace to look like it does on the chart. Here’s what gdalinfo and QGIS identify it as:
Here’s a gallery of what the airspace shape looks like in WGS 84 (the squished one), that California Albers, and the “correct” Lambert projection the FAA uses (with the raster backdrop). The latter two are pretty close, but I could make things hard for myself and use the custom Lambert projection. Instead I’m going to use EPSG:26942, a Lambert that’s centered more or less on San Francisco. Visually the result looks very similar to the FAA’s projection, with the advantage I don’t have to figure out how to add a custom CRS to PostGIS.
5. Create an SVG file with some code. Naively this is as simple as ST_AsSVG(geom) and pasting the path into a skeleton SVG document. This actually works, but is a bit awkward since without reprojection the coordinates are all lat/lon values and stuff’s in a box from 37, -115 to 40, -118 or so. Quick workaround for that in Inkscape: select all (Ctrl-A) then zoom to selection (3). Also need to set the stroke width to something sensible for the coordinates.
Having to stop work on this here; I’m now generating reasonable SVG files, one per chunk of Bravo. Two main things left to do. First, use SVG transforms to scale the shapes from the default extent numbers like x=2,000,000 y=464,000 to something like 7cm square Ponoko uses. And second, do some topology calculations with ST_Union or the like so I render each slice of the airspace cake for every elevation.
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.
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.
I thought it’d be “fun” to upgrade from PostGIS 1.5 to 2.x on my Ubuntu box. I forgot how byzantine Postgres extensions are and the fundamental rule of database upgrades; you have to take a dump with the old version first. I didn’t take careful notes, but here’s what sort of worked for me.
Read the PostGIS instructions on upgrading, in particular the notes about doing a “hard upgrade”. Create a dump before changing PostGIS 1.5.
Follow these instructions on installing PostGIS 2.x from sharpie’s PPA. You really need postgis-nightly; he has a PPA called postgis-stable too but I don’t think it’s fully populated.
Restore the dump with pg_restore, to a new database name. Pay close attention to stderr.
I got an error about ST_* functions being “not unique”. This report suggested that the restore brought over some 1.5 versions of functions and the solution is to run postgis_upgrade_20_minor.sql. Running that threw errors because I had a view depending on some of the functions; I ended up just dropping the view.
Honestly this is all pretty messy and I don’t have full confidence that PostGIS 2 is really installed properly. There’s too many spooky places PostGIS stuff gets loaded into the database. But all my old code still seems to work and gives the same results (at least, visually) so maybe it worked out.
I tried playing with ST_ConcaveHull that I wanted. It’s very, very slow on a GPS track with 50 points in it. Like 1.5 seconds to do a single track to a target percent of 0.5. I guess it’s doing some optimization algorithm? target percent of 0 doesn’t even work, throws a TopologyException. This function may not be what I need to do my calculation.
select
ogc_fid,
ST_NPoints(ST_Simplify(wkb_geometry, 0.0002)),
ST_ConcaveHull(ST_Simplify(wkb_geometry, 0.0002), 0.5) as wkb_geometry,
name
from tracks
limit 1;
It’s hot. Here’s an animated map of temperatures for the day, from the aviation forecast. Normally this kind of angry rainbow palette is the worst sort of visualization sin, but it’s sort of appropriate for a hot day like today.
Making an animated GIF well is harder than I remember if you care about filesize.
I got my lasercut test back. It worked out pretty well.
I was surprised at how well the fine detail came out on the GPS track. One blob is missing; I had a widowed little lozenge at bottom right that was detached. Fair enough. But all the fine details came out surprisingly well on the cardstock. The letters came out great too; all I did was convert some Postscript font text to a path and it came out fine.
The thing that didn’t work was the SF Bravo space (see earlier post). Entirely because of the double lines; Ponoko warns against doing that and they’re right. I also didn’t like the cardstock itself, particularly the burnt edges from the laser. To be expected, and no big deal since this was just a test cut, but unappealing. The solid grey areas came out surprisingly well; they sort of half burn it with the laser and it looked OK. Surprisingly the results came back glued to a wax paper back that I think was attached during the burning. Nice for not losing small parts, and frankly I’m amazed they can tune the laser so it cuts through the material but not the paper backing. I wonder how well that works with something like plexiglass.
Next project will be to re-do the Bravo, but do it right this time. First, use the right projection so the circles aren’t ovals! Second, create a series of stacked objects, one layer for each 1000′ of altitude. That’ll require some union magic in PostGIS. My goal is to get a stack of plexiglass layers with a hole in the middle so I can make a proper 3d object.
I’m playing with doing some lasercutting, using Ponoko and their Inkscape starter kit to do the cutting. I gave myself just a few hours to prepare a single test file to send off for fabrication, just to get my feet wet. First time using Inkscape, and first time in over 10 years to try to drive a laser cutter.
Inkscape is sadness on a Mac. It runs in X11 which is mostly intolerable. It’s unaware of the Mac file system. But the worst thing is the rendering is just really ugly. It’s a shame there’s no Cocoa native port of Inkscape, although realistically that’d be a lot of work to do right. BTW is it just me or if you copy a path from one Inkscape window and paste it to another, does it get converted to a bitmap?! I had to save the thing to a file and then import it to preserve the vector data.
Ponoko’s use of Inkscape is quite simple. Basically just make a bunch of blue lines 0.01mm wide for cuts. Some extra options for engraving, fills, etc. I made some circles and an outline of my name in Futura as test objects. But on to the more interesting things.
First, my walks tracks. Converting my complex walk shape to a cuttable SVG was not easy. The GPS tracks themselves are not sensibly cuttable, of course, you’d end up with confetti in the middle. What I want is to cut the concave hull of my shape, plus do something clever to depict some internal structure. Not sure how to do that. Even concave hull isn’t easy; ST_ConcaveHull isn’t available until PostGIS 2.0 which I’m not yet using. So what I did was use a combination of QGIS and Inkscape to make a filled shape of all my walks, a raster blob, then use Inkscape’s bitmap tracer to turn that into an outline path. Even then I got kind of a mess, had to go in and remove a lot of points. I’ve still got a disjoint lobe in my object which is going to screw up the cut, but I left it in there because I was curious what would happen and I don’t know how to easily fix it anyway.
Second the San Francisco Bravo airspace. This was pretty straightforward; load up the shapefile from FADDS in QGIS, print it to SVG, done! Well almost; that results in a bunch of lines being double-drawn, which causes the laser to cut twice. Ponoko doesn’t want you to do that and has instructions on how to manually break up shapes so duplicate lines don’t print. I did my best but I probably missed some spots.
OK, my SVG file is done, ready to cut! Now then, what material? Ponoko has a fun variety of options. Cardboard would be the natural cheap material for testing, but it’s kind of flimsy for some of the fine angles and they recommend not using the raster engraving option, which I’d already done as test images. I went with cardstock on the theory it’d be most forgiving to any materials / delicacy problems.
Some sample prices for my relatively simple object, 7.1″ square material sheet. Prices are “making”, which I take to be laser time, and then the material.
Cardstock: $7.13 + $2.36.
Thin cardboard: $7.93 + $0.23.
Cherry veneer MDF: $14.83 + $4.34.
Fluorescent orange acrylic: $8.27 + $3.72.
Bamboo: $8.27 + $2.82.
$10 for the item and another $10 for shipping and the order is in! They say it takes “typically 1-2 weeks”, but I see there’s a design review first which will presumably take some time on their end and maybe mine.
Kartograph is looking promising. It’s a new Javascript map library that is fully vector based, drawing maps in SVG. First time I’ve seen a complete break with the slippy map raster tiles that Google made so popular. The nice thing about a vector map is you can easily use your own projection. Of course you can do raster tiles in many projections too, but most of the existing raster libraries have Google Mercator baked pretty deeply into them. Also vector rendering is beautiful and somewhat scale invariant.
The code’s on GitHub. And if you dig into the demo pages you can find the source code hidden inside the <div> element that contains the map itself. It looks pretty straightforward, a nice API. I’m a bit alarmed to see methods like “chloropleth” and “dotgrid” right on the map object; that suggests the author has in mind a set of hardcoded visualization types. I hope he’s left room for other developers to easily add their own visualization types. Also none of the examples have any navigation, none of the usual pan/zoom controls we expect. That’s totally fine for many visualizations, but may distinguish the uses of this library compared to Leaflet and friends.
Green lines are foothpaths, dashed white lines are steps. Particularly clear in right center, the steps leading up to Bernal Hill. I don’t see my beloved Harry Street steps, maybe they’re not in the 2010 dataset this map is based on.
More on Skunk Alley; I was talking to Eric F and he was saying it was a shame that this path wasn’t already in OSM. San Francisco publishes a shapefile of street centerlines; apparently when that was imported via TIGER into OSM they filtered out stuff that wasn’t quite a street, like unimproved rights-of-way. And indeed my second, southern segment of Skunk Alley is in that shapefile, as “UNNAMED 025” with CNN 19211000.
So that begs the question; what’s in the SF shapefile that’s not in OSM? Answering that question correctly requires a bit more geometric fiddling in PostGIS than I know how to do yet, but I did get a quick and dirty picture by using QGIS by drawing the OSM data in black on top of the SFData shapefile in purple. Anything purple peeking through is in the difference (roughly)
Lots of little snips and bits in the SF shapefile that aren’t in the OSM. Interesting! I should figure out how to use PostGIS to give me the actual difference.
While preparing this map I had to fix it so that Church street showed up. I used to draw everything with “railway is null”, but somehow that leaves out Church St. Maybe because it has a Muni track running down it? But with railways turned on you get things like underground subways (BART), the old abandoned track snaking through the Mission, etc. Haven’t found a reliable way to filter all that out yet; need to revisit HighRoad’s canned queries for that.
I’m liking how my map of walks is turning out. It’s now useful to me in that I can see what streets I’ve walked on and what I haven’t. It’s also sort of pretty. I particularly like how the GPS error gives a random smudge effect to the paths. Transparency for older tracks works nicely. I’ve tried to induce some hue variance just to let the eye pick out individual tracks, but the orange->red scale is a bit lipsticky and seems to demand the question of exactly what hue represents (track length).
I added a walkway to OSM today, Skunk Alley, a funky little path between two houses with a hand painted sign. It’s on land that’s not part of a house lot and goes through a convenient location, so I think it makes sense to have it marked in the map as an actual walkway.
Skunk Alley is tagged “highway=track, surface=dirt”. I’d never seen the surface tag before, it’s not a column in the SQL version of the OSM Metro extracts I’m using. But highway=’track’ is a useful clue. Here’s all the various kinds of highways that look to mean “a way you walk on but can’t drive”.
select highway, count(*) as n
from planet_osm_line where
"highway" IN ('pedestrian', 'track', 'path', 'footway', 'bridleway')
group by highway
order by n desc;
"footway";5252
"path";1063
"track";959
"pedestrian";116
"bridleway";2
I gather from stuff I read that highway=path is not loved in the OSM community.
Here’s a map of most of SF with those 5 types of highway coloured. Purple is “footway” and seems to apply both to walking tracks in parks and the occasional street-type walkway (like along San Jose Avenue, bottom middle). Light blue is “path” and has useful walkways. Brown is “track” and dark blue is everything “pedestrian” and “bridleway”. The distinction between them all seems entirely arbitrary. Fort Funston is all “tracks”, the zoo and Golden Gate Park is all “footways”, and the greenspace west of Stanyan & 17th gets “paths”.
I’m liking Leaflet. It’s got all the great flexibility I love in Polymaps, quickly compositing various layers of raster and vector data into one fancy map. But unlike Polymaps it runs well on iOS devices. And it’s got an active community; Polymaps feels like a dead end.
A few things are missing:
There’s no way to specify the z-ordering of layers, it’s all just in whatever order they are. The developers have said they’re working on this. (Z ordering basically doesn’t exist in SVG, it’s all document order. That’s dumb.)
Scaling transitions aren’t beautiful. Leaflet animates the raster layer but hides my vectors and then has them blink back into place. Bah.
Screenshot of work in progress. Lots going on here... Purple is steps. Orange squiggles are my walks. Faded = older walks. Redder = longer walks. There’s some interaction, too. Click on a track to highlight it and get a popup showing length and age.
I keep playing with this dataset of all the steps of San Francisco from OpenStreetMap. I made a GeoJSON file with all the steps of San Francisco. It’s a snap to add to a Web map with Leaflet. A few thoughts:
GeoJSON is a good format for geodata when you’re working cross-language. PostGIS can emit it, Python and Javascript can easily parse it, Leaflet can easily draw it. Half the time I just get a string from PostGIS and never even parse it in Python, just pass it along.
The Python geojson library doesn’t really help very much. If you’re using geopy already to work with geodata, then maybe it’s helpful. But if you’re just building up arbitrary JSON blobs with some geodata it’s not needed.
The world could use a GeoJSON validator. Extra credit if it rendered the GeoJSON blob on a map, wouldn’t be too hard. I should set this up as a web service.
JSON float precision continues to contribute to file bloat; Python’s default 15 digits precision translates to subatomic location positioning. Fortunately in Python 2.7 it’s pretty easy to round off numbers, you just have to do it.
The GeoJSON format I settled on was a FeatureCollection. Each feature has the name, length (in metres), and OSM ID of one set of steps. Then two geometries: the centroid of the steps and the path of the steps. Example:
Here’s the SQL query for all the steps I’m using. There’s more Python code than I’d like to collect all these rows and emit the GeoJSON, but I’m not pasting it all here.
select
planet_osm_line.name,
ST_Length(planet_osm_line.way) as meters,
ST_AsGeoJSON(ST_Transform(ST_Centroid(planet_osm_line.way),4326), 6),
ST_AsGeoJSON(ST_Transform(planet_osm_line.way, 4326), 6),
planet_osm_line.osm_id
from planet_osm_line
inner join planet_osm_polygon
on ST_Intersects(planet_osm_line.way, planet_osm_polygon.way)
where
planet_osm_polygon.osm_id = '-111968'
and planet_osm_line.highway = 'steps'
order by meters desc;
I’m exploring Leaflet as an alternative to Polymaps, mostly because Leaflet has some momentum and is faster to render on iOS. here’s a quick demo of drawing a raster map with a GeoJSON overlay.
var map = new L.Map('map');
var rasterLayer = new L.TileLayer('http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg', {
attribution: 'Stamen Terrain',
maxZoom: 18
});
var view = new L.LatLng(37.75, -122.43); // geographical point (longitude and latitude)
var trackLayer = new L.GeoJSON(track);
map.setView(view, 14);
map.addLayer(rasterLayer);
map.addLayer(trackLayer);
“track” was preloaded as a JSONP script. ogr2ogr barfs on converting my GPX files from Runkeeper directly to GeoJSON, so I exported them out of PostGIS instead with
select ST_AsGeoJSON(wkb_geometry)
from tracks
where name like '%4/21/12%'
Leaflet uses SVG for the GeoJSON layer. Pretty simple structure, svg > g > path, I think one per GPS track.
With just a bit more work it was easy to load 65 walking tracks via Ajax (165k data total) and plot them all in a browser. Performance is pretty good on iOS; the main thing I don’t like is the way the GeoJSON layers disappear during a resize.
I moved a road. OpenStreetMap had one path for an obscure little road in Nevada City, CA called Woodwardia Place. I was curious about the exact path so I drove down it twice with a GPS logger, then used JOSM to upload a change. It’s cool how fast the upload took effect; the raster tiles for the map were generated anew within 30 seconds of my upload. JOSM is a bit confusing, and I never could figure out how to upload the GPX track for OSM’s records.
Here’s the edit; old road is in grey, new road is in yellow moved slightly north.
Then I split the road. There’s a segment that’s a bridge, so I made a change that split the road into two ways and then tagged the short bridge segment with bridge=yes.
Finally I went to a different part of the map and removed a road segment. I’d driven blind down that road expecting it to go through, but the map was wrong. Never again! Removing a road segment is a bit tricky; I had to select the node on the western (non-existent) T intersection, “unglue it”, delete the incorrect line segments, then “merge nodes” to reglue the now-T intersection that does exist on the map.
I have a bunch of GPX tracks generated by iSmoothRun, a GPS tracker for the iPhone that tries to correct for location error by using the accelerometer as a pedometer. The tracks it produces are pretty lumpy too, so I’m trying to use ST_Simplify afterwards to clean them up.
ST_Simplify takes as a second parameter the “tolerance”, how much to smooth. This parameter is not well documented but it seems to be measured in the units of the geometry you are simplifying. For my walking tracks 0.00005 seems to be about right. If that were degrees, that’d correspond to about 15 - 20′ in San Francisco.
Here’s a quicky chart of the average percentage difference between the original track length and the simplified track length, for different tolerances.
0.00005 seems to be a reasonable compromise. It produces tracks with about 1/3 the number of points as the original. Below is a picture of the original track and the simplified drawn on top of it, to show the geometry change.
I wish I understood SRIDs more intuitively, I feel like I’m bashing about. Half my data is WGS84 and half is Google Mercator, and then below I’m using SRID 2163 to do the distance calculation. That’s a bit of cargo cult coding, I think it’s NAD83 which is close enough to WGS84 to get away with.
-- Create a simplified view of an ogr2ogr imported track
create or replace view simple_tracks as
select
ogc_fid,
ST_Simplify(wkb_geometry,0.0001) as wkb_geometry,
name
from tracks;
-- Display the difference between original and simplified
select
miles-smiles as difference,
round((miles-smiles)/miles*100) as pctlength,
round(spoints*100/points) as pctpoints,
* from
(select
tracks.name,
ST_Length(ST_Transform(simple_tracks.wkb_geometry, 2163)) /1609 as smiles,
ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles,
ST_NPoints(simple_tracks.wkb_geometry) as spoints,
ST_NPoints(tracks.wkb_geometry) as points
from simple_tracks inner join tracks
on simple_tracks.name = tracks.name order by name) as m;
-- Calculate just the average difference
select avg((miles-smiles)/miles*100) from
(select
tracks.name,
ST_Length(ST_Transform(simple_tracks.wkb_geometry, 2163)) /1609 as smiles,
ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple_tracks inner join tracks
on simple_tracks.name = tracks.name order by name) as m
where miles > 1;
I imported 60 different GPX tracks from RunKeeper into my database, using this hack. I’ve been dorking around with the data using TileMill as a sort of GIS app; it’s nicer than QGIS! But it’s silly for me to try to draw my own complete map from OSM data, as fun as that is, so I’ll probably switch to some GeoJSON overlay on top of a slippy map with nice terrain tiles next. Anyway, here’s a map of just the walks and then parks in SF.
I like the way the transparency + the GPS noise naturally shows streets I walk on more frequently.
I improved my query for all the steps in San Francisco, by narrowing it down to steps that are really just in the city of SF itself and not whatever happens to be in the OSM Metro import I have in my database.
First I had to find where in the database was the actual boundary of San Francisco:
select name, * from planet_osm_polygon where boundary = 'administrative';
Visually inspecting that list turns up OSM_ID -111968, San Francisco. Below is a quick drawing of that polygon in OSM. It’s not quite correct; all the water is fine, but it leaves out the Farallons and includes a tiny bit of Alameda and Angel Island. Still, close enough.
Then it’s just a matter of doing the geographic intersection. This query makes me scratch my SQL head a little bit, I cribbed it from the PostGIS book, but it runs pretty fast. Much slower if you try this intersection on all the roads in the SF Metro.
select
planet_osm_line.name, round(ST_Length(planet_osm_line.way)) as meters, planet_osm_line.osm_id
from planet_osm_line
inner join planet_osm_polygon
on ST_Intersects(planet_osm_line.way, planet_osm_polygon.way)
where planet_osm_polygon.osm_id = '-111968'
and planet_osm_line.highway = 'steps'
order by meters desc;
There’s a bunch of location tracking apps now, all of which basically collect where you are all the time in a casual way. The key thing is that they only sample location occasionally, to save battery life.
I did a 15 minute drive in San Francisco today, then a 40 minute walk home. About 2.5 miles each way. I was running four of these tracking apps at once on my iPhone, to compare how much data they logged.
Google Latitude: 12 points
Geoloqi (Battery saver mode): 4 points
OpenPaths: 6 points
They all sampled roughly the same amount of data, although the extra resolution from Latitude makes a big difference in the final picture. None of them captured any points at all when I was driving. I’d hoped these apps would realize I was moving quickly and start sampling more frequently but, well, no.
I wonder if there’s a direct correlation between sampling rate and battery consumption. Google Latitude does use more battery than Geoloqi, but I’m not sure how much more. Haven’t really tried OpenPaths yet.
Here’s screenshots of the maps each tracker generated, along with a detailed track from iSmoothRun.
I was curious about what ways in OpenStreetMap were defined as Steps, so I did some basic queries and maps and reports. The query’s overly broad, I need to learn how to intersect that with the actual city of SF.
select
name, round(ST_Length(way)) as meters, osm_id
from planet_osm_line
where highway = 'steps'
order by meters desc;
To better understand the OSM schema, I did a bunch of queries to find out which columns in which tables actually contained meaningful data. Kind of like the query about highway types I did, but for every single column. Then I went through by hand and copied out the “interesting” columns, ones that seemed to have a lot of data.
Here’s a big list by table, then column, then the distribution of the values in that column. SF Metro only. One thing that’s clear; even in SF the data’s not complete enough to be an unbiased sample. For instance you can’t tell from OSM how many Jewish synagogues there are vs. how many Christian churches, the data’s just not complete enough.
I had a little todo item today, “Edit OpenStreetMap”. Thought it’d be fun to try out the editor. After 10 minutes I declare failure with Potlatch; the Flash app on the main server is so terribly slow as to be unusable. I need to read the Beginner’s Guide and other editing options.
After a bit of patience, Potlatch loaded usefully. I ended up editing the map to put a name on the tiny little Duncan-Castro park. I hope I did this right, the UI for adding a name to a park is not clear. I ended up using the Advanced view to add a name=Duncan-Castro field to the list for the way.
My big plan was to edit one of the 6000+ entries in the SF Metro extract that have no “highway” tagged on them. Turns out that’s not necessary; they tend to be other features, like creeks or county boundaries or stuff. D’oh.
I did find one entry for an uncategorized “Center Street” in SF, osm_id 8489931. But there’s so many other overlapping “Center Streets” in the database I think the fact this one is untagged is not a problem.
select
name,
ST_Length(ST_Transform(way, 2163))/1609 as miles
from planet_osm_line
where
highway is null
order by miles desc;
"Golden Gate National Recreation Area";50.114480677903
"";50.1127120036684
"San Francisco";50.1127120036684
"San Mateo County";49.8960294825062
"";49.6164354346274
"Alameda County";49.5445744035326
"";49.3526266530211
"San Francisco County";49.3158064558191
"";49.2591797769354
"";49.2302041734416
"";49.2049183432214
"";49.1809376585467
"";49.0948344172935
I revisted my earlier OSM experiment only using TileMill instead of QuantumGIS to make the map. TileMill has much nicer output, particularly if you want to ship a set of slippy map tiles or frame out specific high quality images / prints. It’s also more of a textual programming kind of paradigm, which I like better. OTOH TileMill also has very specific limits on what it’s capable of doing; it’s not a generic GIS toolset.
It was pretty easy; the hardest part was remembering the weird way to filter a table with select in TileMill; their PostGIS support is a bit idiosyncratic. Also it guessed wrong on the SRS for my tracks; they’re in WGS84 but it was trying to draw them as if they were in Google Mercator, way out of scale. That seems like a bug.
Anyway, I remade my map of my walks around SF, here’s an image and some code.
OpenStreetMap is all kinds of awesome, but boy the data schema is a mess. planet_osm_roads doesn’t really contain all the roads, you want planet_osm_line. (Yes, one name is singular, one is plural). planet_osm_line sure contains a lot of lines, what are they all? The “highway” column tells you. here’s the most popular types of “highway” in the San Francisco metro extract.
It’s not terrible; things that are correctly classified really are. But “all roads” requires identifying several classes, there’s some ambiguity, and some stuff clearly doesn’t belong there. Still the data exists and is free, so I shouldn’t complain too much!
(Migurski’s High Road is a set of SQL views that present a cleaner schema of roads. But just roads, nothing else.)
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
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.
Mike pointed me to an interesting slide deck by Leland Brown in October 2010, about using a fractional Laplacian to colour a terrain map instead of the usual altitude greyscale or hill shading. The results are pretty nice and the presentation of how he did it is quite clear.
Conceptually, what he’s doing is a bit like a standard altitude greyscale. Ie: 0′ is black, 15,000′ is white, and use a grey ramp inbetween. But the transform he applies highlights local terrain differences. Ie: the shade of a pixel isn’t just its absolute altitude, but also how it differs based on its neighboring pixels. It’s a little analagous to edge enhancement on an image: find regions of high variance and highlight them. The result is a map that’s essentially altitude coloured, but with highlighting of local terrain details.
One nice aspect of the math he’s using is that it’s scale invariant. That means the algorithm makes sense at all scales and, also, doesn’t need to be recalculated at different scales.
The computation is more expensive than hill shading but not terrible: he says he can do 10,000 x 10,000 pixels in a few minutes. He notes at the end it’s a bit tricky to do this with tiled data, because you should consider data outside the tile itself when doing the rendering.
I wanted to play with contours for some mapping. Ie: a shapefile of where the 8000′ or higher terrain is across the US. Turns out to be pretty simple to generate something basically working from SRTM data. The gdal_contour program does the work. The OpenStreetMap folks have some nice notes on how to use it with SRTM data. The details, however, are much harder.
Basics
$ gdal_contour -a elevation N40W108.hgt N40W108.shp -i 304.8 -snodata 32767
That generates 1000′ contours, very fast, maybe 150ms with the data in cache. The output file size varies wildly: for that hilly part of Colorado it’s 1 meg. Generating 100′ contours instead takes about 6x as long and results in 10x the resulting file size. (gdal_contour is dumb about files: if the output file already exists, the error you get is “ERROR 1: N40W108.shp is not a directory”)
North America has 2415 data files so even on a slow computer 1000′ contours can be generated in about an hour. Once you have the contour shapefiles, you can import them into PostGIS. It goes pretty easily, but is slower than generating the shape files themselves. Should probably create an index, too.
$ shp2pgsql -p N20W076.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N20W076.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N20W075.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N19W075.hgt.shp srtm_contours | psql contours
$ shp2pgsql -a N19W076.hgt.shp srtm_contours | psql contours
The import of all of North America took a couple of hours and the table is 14 gigs on disk. 32,865,353 rows. Some quick efforts to make maps with TileMill suggest it’s too much data. Need indexing on elevation and the geometry, also would really like to simplify those contour lines.
Thinking in feet
The elevations are in meters, stored as a double, but I think in feet and it’d be nice to simplify. So let’s convert them to integer feet and index on elevation.
alter table srtm_contours add column elevation_feet integer;
update srtm_contours set elevation_feet = round(3.28084*elevation);
This is very slow, over an hour. PostgreSQL is completely copying the whole table to make rows with the new column. Maybe it would have been better to update the value in place.
Indexing the data
Let’s create a basic spatial index!
create index idx_srtm_contours_the_geom on srtm_contours using gist(the_geom); -- about 30 minutes, 2 gigs
vacuum analyze srtm_contours; -- 30+ minutes, at least before database tuning
Subsetting for TileMill
Even with the index the contours are just way, way too much for TileMill. I’m not sure how smart TileMill is about querying only data it needs. A different solution is to create a special table with just rows for the 8000′ elevation level (the one we care about). It also seems to help to simplify the contours some.
create table contour_8000_simple (
gid integer,
id integer,
the_geom geometry,
constraint contour_8000_pk primary key (gid)
);
insert into contour_8000_simple
select gid, id, ST_SimplifyPreserveTopology(the_geom, 0.001) from srtm_contours where elevation_feet = 8000;
(SQL is approximate, not cut-and-paste ready). The 0.001 parameter means “simplify to 0.001 degree”, in this case.
Next Steps
After all the selecting and simplifying the resulting data works OK in TileMill. It renders at an acceptable speed, at least, and if you draw big fat lines you can schmudge over the awkward too-detailed contour. But this work has gotten pretty hacky. I really need polygons, not linestrings, so I can fill the 8000′+ range. But because the contours were calculated on 1degree square tiles in the first place, closing the polygons takes a bit of work. Also I haven’t dealt properly with NODATA regions. Need to sit down and re-do it with more time.
Here’s what it looks like, for a region of mountains SE of Salt Lake City, UT.
I’m playing around with drawing airspace. The FADDS database has nice ESRI shapefiles for B, C, D, and E. Easy to use them directly with QuantumGIS or TileMill, or import them into PostGIS, or whatever. But they don’t publish special use airspace in shapefile format.
$ ogr2ogr -f "ESRI Shapefile" allusa allusa.v11.08-25.1.txt
$ shp2pgsql -s 4326 airspaces.shp | psql faadata
$ echo '\d airspaces' | psql faadata
gid | integer |
class | character varying(80) |
name | character varying(80) |
floor | character varying(80) |
ceiling | character varying(80) |
the_geom | geometry |
$ echo 'select class, count(*) from airspaces group by class' | psql faadata
class | count
-------+-------
Q | 456
B | 341
P | 12
C | 321
R | 417
D | 550
Classes.. B, C, and D are Bravo, Charlie, and Delta. P is prohibited, R is restricted, Q is “danger” (MOAs and Alert areas, I think). Name is free text. Floor and ceiling are also free text, things like “SFC”, “12500 MSL”, “300 AGL”, and “FL 180”.
FADDS does provide the special use airspace geometry in a couple of formats. There’s SUA.txt (10 megs), an old text format that ogr2ogr doesn’t seem to support. (The “SUA” driver is something else). There’s also the new SAA AIXM files. They are in FADDS and ogr2ogr has some support for them, but a quick test made it seem pretty inconvenient to use the data. (Update: I wrote Lynn, who makes the Soaring Web files, and she says she wrote her own complex code to handle SUA.txt)
I’m playing with TileMill (see my blog post here). TileMill publishes to an mbtiles file, a sqlite3 database that contains the rendered image tiles. One simple file, so nice! Now, how to serve it? The simplest solution is TileStream hosting, but I’m too cheap and hackish to pay the very reasonable $50 / month.
So I set up a tile server on TileStache instead, a Python system. You can see the setup on GitHub. It took about four hours to get working, even though none of it is too complex. Here’s my notes.
Install TileStache via Python easy_install and configure. It’s pretty simple, the only subtle thing is that TileStache wants a cache. This may not be necessary with pre-rendered mbtiles bundles but it was easy enough to set up memcached and configure it.
Set up TileStache to render via CGI, with a CGI script and a bit of Apache config. CGI is a bad way to serve things, but I’d hoped it was sufficient and it was easy to get going. Turns out to be unacceptably slow.
I tried a couple of failed approaches for WSGI. First I tried TileStache’s built in WerkZeug server. This works and is faster than CGI, but lacks administrative scripts to wrap it. Then I tried Apache WSGI and ran into an error with no useful debug output. Gave up on that.
Set up gunicorn, the excellent Python asynchronous server for WSGI. It’s easy to set up on Debian if you get version 0.13 from Backports, it comes with nice administration scripts. Just needs a little config file. I also installed python-gevent for an async worker.
Doing all this, my crappy old single CPU server with 1 gig of RAM can handle serving a map to a single user at acceptable speed. It can probably do more than that, I haven’t load tested it.
I left some things not done, this was intended as a quick hack:
gunicorn really wants a proxy HTTP server like nginx in front of it. Good idea, but I didn’t want to bother. The bummer is gunicorn doesn’t set any caching headers at all; really need those for a real deployment.
The cool kids building TileMill are doing everything with Node.js these days. Their TileStream server would be another option, but getting Node running on Debian was too much work for a quick hack.
It’s a little surprising that MBTiles is so complex to serve. It’s basically just a big archive of JPG images, it’d be nice to have a little C program to serve it blindingly fast. “mbserv foo.mbtiles --port 8989”. TileStache is a big program that does a lot of stuff, but even TileStream is 900+ lines of code and all it does is serve MBTiles.
Doing some research on Digital Elevation Models, for making terrain maps.
SRTM
(Wikipedia, OSM Wiki) sourced from a space shuttle overflight in 2000. Comes in several flavours and sources.
Sources:
NASA source (download link). Original data. Version 2.1 is their latest, cleaned up by NGA. The NASA has some data voids, particularly at mountains and lakes. Documentation of the dataset. License: Data said to be fully open for any use; don’t have a specific reference.
CGIAR-CSI Data processed to remove voids. SRTM3 only. They publish it as “version 4.1”, version number reflects their data cleaning. Also available as an Amazon EBS volume. License: non-commercial with attribution.
HydroSHEDS. SRTM data with voids filled, SRTM3 only. Also vector data on watersheds. Technical documentation.
License: “free for non-commercial use”
Details on NASA source:
SRTM1:
Resolution: 1 arc second, roughly 30m, z=12
Format: .HGT files, 3601x3601 per one degree square file. Each sample is 16 bits, height in meters (-32768 for no data). GDAL supports this format.
Coverage: Continental US, a bit of Alaska, and various US territories. Coverage map.
Size: 1117 files of 25 megs each, or 27 GB uncompressed. 2:1 compression with gzip.
SRTM3:
Resolution: 3 arc seconds, roughly 90m, z=10
Format: .HGT files as SRTM, 1201x1201 per one degree square file.
Coverage: global land mass from 60N to 56S. (Missing Antarctica, significant Northern parts of North America, Europe and Asia). Coverage map.
Size: 14546 files of 2.8 megs each, or 39 GB. 2:1 compression with gzip.
SRTM30:
Resolution: 30 arc seconds, roughly 1km, z=7
Coverage: global from 90N to 60S. (Missing Antarctica). Coverage map. See also GTOPO30.
Joint NASA/Japan METI project, produces a 30m DEM. (Wikipedia, OSM Wiki) Has coverage between 83N to 83S and some holes filled compared to SRTM. Some question on quality; the data comes with a “quality assessment file”. May be free to use, but some concern on the OSM Wiki that its license is not consistent.
USGS project. Global data: 90S to 83N. 7.5 arc second (30m). Looks to be a combination of SRTM data and other sources. License is presumably public domainish. The metadata page says “Metadata access constraints: No restrictions, All GMTED2010 data products and associated metadata are publically available”.
Downloaded the rectified TIFFs from the Army. These have already been rotated and georeferenced and are pretty high resolution. The p22* files are the maps I worked with.
Created pyramidal overviews for the TIFFs so I could explore them in QuantumGIS more quickly. Not strictly necessary, and in fact may be harmful: gdal2tiles seems to pick up the JPG compression.
gdaladdo -r average --config COMPRESS_OVERVIEW JPEG --config PHOTOMETRIC_OVERVIEW YCBCR --config INTERLEAVE_OVERVIEW PIXEL -ro p22_s12.tif 2 4 8 16 32
Created a virtual raster layer including properly annotated sections of no data
gdalbuildvrt -srcnodata “255 255 255” fisk.vrt *.tif
At that point, I was done! gdal2tiles.py includes a Google maps interface that works. Of course I couldn’t leave well enough alone, so I wrote my own Javascript interface using Polymaps.
Some other caveats and notes:
Data quickly gets big and slow. The source map is only 32 megs of TIFFs, maybe 10,000 x 150,000 pixels. But all the cutting and repackaging and uploading is going to take hours. I did OK experimenting with a small subset (just 2 TIFFs of 15). I decided to cut the render to z=13 instead of going full resolution to z=14: 4x speedup! (Final result: roughly 6 hours CPU, 230 megs of GIFs for the tiles).
The source TIFFs include page margins. A proper seamless map would require cutting those off by hand. I didn’t bother for this quick hack.
Output image format is a problem. The default PNG output of gdal2tiles is enormous. Some details, including file size of the tileset for a sample input of only 2 of the TIFFs
32 megs: source TIFFs (sheets 12 and 13 only)
60 megs: gdal2tiles output, 24 bit PNGs with transparency. (was 220 megs at z=14)
50 megs: optipng. Doesn’t help as much as I need, only 10-20%.
15 megs: JPG. These would be awesome, but I need transparency because the source maps aren’t rectangular
24 megs: 8 bit PNGs with transparency. Unfortunately imagemagick’s PNG8 conversion is buggy, particularly with transparency, and I can’t use it.
convert foo.png PNG8:foo-8.png
28 megs: GIFs. imagemagick does a good job emitting GIFs with transparency.
When you make a backup of an iPhone, it creates a big directory full of files with random 160 bit filenames. These are named files in the iPhone that iphonels.py can display. My 3 biggest files are named
HomeDomain::Library/Caches/com.apple.WebAppCache/ApplicationCache.db
AppDomain-com.foreflight.ForeFlightMobile::Documents/Procedures.zip
RootDomain::Library/Caches/locationd/consolidated.db
consolidated.db is the file with the location data in it. It’s a sqlite3 database.
The juicy tables are (apparently) CellLocation and WifiLocation. The *Counts tables seem to contain just a row count. Presumably the Boxes tables are some sort of spatial index. I can find no record of how often I was at a specific location other than what’s implicit in the timestamps and density of cell/wifi locations.
I have 32,013 rows in CellLocation, 171,040 rows in WifiLocation
Timestamps are like 309803342: I believe this is NSDate seconds since 1 Jan 2001. Add 978307200 to get it in seconds since Unix 1970 epoch.
HorizontalAccuracy varies from 50-300 for WifiLocation, and up to 80,000 for CellLocation.
Confidence is 0, 50, 60, 65, 68, or 70
Speed and Course are always -1 (no surprise).
Some quicky sqlite3 shell code
.mode csv
.output wifilocation.csv
select Timestamp, Latitude, Longitude from WifiLocation order by Timestamp;
.output CellLocation.csv
select Timestamp, Latitude, Longitude from CellLocation order by Timestamp;
I have some friends who track their positions via ham radio on APRS. Cool stuff. The site http//aprs.fi/ has a really nice map viewer of the data. I’m looking at extracting that data for my flight tracker.
The easy way is to have the user use the data export tool to download a file. It’s a bit awkward and manual but easy to understand. There are multiple format options, CSV seems sufficient. Fields are:
time: full text UTC, “when the target first reported this (current) position”
lasttime: identical to time in my data. “the time when the target last reported this (current) position”
The granularity of track data is up to the APRS sender. I think one fix every 5 seconds is considered fast. My friend’s tracker is smart enough to send more rapid updates when turning, etc. 66 points for a 90 minute flight.
There are other sources of this data. aprs.fi notes you can also get the data directly from APRS-IS via a library like Ham-APRS-FAP. There’s also aprsworld.com; Adam Fast has some nice API code that relies on his having database access to aprsworld.
I’m trying to launch a map project that uses another site’s map tiles in Polymaps. Here’s links to licensing details for various tile options, along with my very cursory understanding based on my non-expert quick read of their licenses.
Google Maps API: various limits, the most important being you are required to use their Javascript library. Or so I’m told, I didn’t read the license to find the specific language.
Microsoft Bing Maps: you can use their web services with your own code, although the way the metadata service works means you may end up having to display some Microsoft branding, links etc. Education and non-profits seem to have pretty generous usage terms. Commercial use can also proceed without a license agreement, but limited to “500,000 transactions” per year. Beyond that you email them for pricing.
If you overlay OSM data with your own data created from other sources (for example you going out there with a GPS receiver) and the layers are kept separate and independent, and the OSM layer is unchanged, then you may have created a collective work. ... If you have created a collective work, then only the OSM component of the work must be subject to the OSM licence.
CloudMade. Their map tiles are derived from OSM so are similarly CC-A-SA. They may have further restrictions in their ToS.
When comparing my Bad Elf GPS track to my AMOD track, I wanted some mathematical calculation of the difference. I don’t really know even what that’d mean, but matt_c pointed me to some ideas:
Hausdorff Distance (PostGIS, GEOS, explanation). My quick read suggests this will calculate the maximum divergence between the two tracks, not the sum of many little errors.
Fréchet distance. “The Frechet distance is a measure that takes the continuity of shapes into account and, hence, is better suitedthan the Hausdorff distance for curve or surface matching” (source).
I got a Bad Elf GPS for my iPhone. Some notes on using it with MotionX to record tracks:
It seems to work better in airplane mode. First time I tried it, I never got < 50m accuracy, maybe it was still using wifi or 3G positioning? Airplane mode guarantees the only location fix is the Bad Elf GPS.
MotionX seems to be the best GPS tracking software. The UI is awfully non-Apple, but it seems to track well.
I consumed about 60% of my iPhone 3GS battery creating a 2.5 hour long track. GPS had a good view of half the sky (on the glareshield of the plane), airplane mode, doing nothing but running MotionX. I put it manually in Flying mode.
The 2.5 hour track was 260kb of GPX, 132kb of KML.
The MotionX overview of the track says it’s 191.8nm, 2:29:13 elapsed time, avg speed 77kts, max speed 152kts. My (known buggy) calculation on the AMOD log was 196.9nm, 2.3h elapsed, 1.9h in motion.
The Bad Elf + MotionX track looks right. I overlapped it with the AMOD log track and they were mostly on top of each other. Tracks diverged by as much as 16m. Spot check on one specific divergence and the AMOD said it has 10 satellites and HDOP of 1.1, a very accurate fix. Hmm.
GPX file contains a list of fixes: (lon, lat, ele, time). Once in motion it’s one fix every 2 or 3 seconds. The timing discrepancy doesn’t seem to just be a rounding error; I’ve got a sequence of 20:07:13 20:07:15 20:07:18 20:07:20 20:07:22 20:07:24 20:07:27.
KMZ archive contains a “doc.kml” whose main contents are a LineString with (lon, lat, ele). No timestamps. The KML is rendered without altitude by default in Google Earth but you can change the properties to show an extruded track, elevation profile, etc. It appears the elevation is clamped to 0′. It’s not DEM corrected, just a hard-coded 0?
KMZ archive also contains an extra file “raw.xml” which seems to contain raw data, not relevant to Google Earth. But lots of extra data from MotionX! It contains two sections. The XML has “locations”: a list of (time, activeTime, distance, stopped, lat, lon, alt). Time looks accurate to 1ms. activeTime and delta are just deltas from previous locations (it has both 2 and 3s activeTimes) Stopped must be MotionX’s guess of whether we’re moving? The XML also has “recordingSnapshots”, which look to be 1 minute rollups of distance and altitude.
The email also contained a Google Maps link, which incorporates the same KMZ archive as was mailed to me (including raw.xml) served for 6 months from share.gps.motionxlive.com.
MotionX does not seem to record any measure of GPS fix accuracy. Too bad, that data is available in the Apple API. It may be smart enough to automatically filter out fixes with bad data.
I’ve been meaning to measure Bad Elf + GPS when the phone isn’t moving. My first attempt recorded no track, I think because it was clever enough to not record when not moving. Need to investigate Settings / Global: Accelerometrics Assisted GPS, Accuracy Filter.
I get confused as to the difference between coordinate reference systems (CRS) and projections. This overview clued me in some, but I still might be wrong. Here’s my current understanding.
CRS are all about spherical coordinates, naming points on the sphere. When I say “San Francisco is at 37.75, -122.45”, what I’m saying is it’s 37.75 degrees north of the equator of the sphere and 122.45 degrees west of the prime meridian through Greenwich. Points are defined in spherical geometric relation to absolute, fixed locations on the earth.
Only it’s not that simple. First, the earth isn’t a sphere, it’s squashed, and CRS are defined relative to a specific datum that has some oblate spheroid shape with complex geometry. Second, the prime meridian we most commonly use doesn’t go through Greenwich anymore, it goes about 100m east.
The most common CRS in use is WGS84, the basis of GPS navigation. WGS84 itself changes as measurements get more accurate, so the specific thing we all use is WGS84 (G1150). (I’m unclear on how measurement changes are managed; the earth itself is moving, too, making absolute location a slippery concept. See also ITRF2000) The other CRS I’m familiar with from NACO aviation charts is NAD83 (CORS96). It agrees with WGS84 to within two meters and I believe NACO advises treating them as interchangeable. In practice I don’t see any useful reason to do work in anything other than WGS84, unless importing data from some other source that used a different CRS.
Projections are all about planar geometry, warping a spherical map to a flat surface. There’s a large variety of map projections in common use. Mercator is most popular for casual maps and shows up frequently online because it’s what Google Maps (and all slippy maps?) use. Lambert Conformal Conic shows up in NACO sectional charts and USGS sectionals; it’s sort of like a but the projection is parameterized to have the least distortion between two chosen latitudes. Also Lambert Conformal has the nice property that a straight line drawn on the map is very close to a great circle route (shortest distance); handy for airplane navigation.
In maps showing a relatively small area of the Earth, the differences between projections are relatively small. I think I’m inadvertently benefiting from this in my approach plate georeferencing experiments. I’m just treating the plate as if it were drawn in a mercator projection and it looks about right.
Polymaps has the ability to easily pull in raster tiles from various sources to make Slippy maps. I have code that lets me use tiles made by Google, Cloudmade, Bing, GDAL’s tile script, even Minecraft. I have no idea how it works, though. The underlying thing I don’t understand is Polymaps’ internal coordinate representation. Here’s an example, for a map tile centered on San Francisco.
This tells me Polymaps is natively using Google’s coordinate system. TMS is similar but numbered differently, here’s my cargo cult code to work with it. Mike tells me 1 << c.zoom is the number of tiles at the given zoom level, which explains why it’s used as a modulus everywhere.
// Set X to c.column, but wrapped around in the range [0, numTiles)
var x = c.column % (1 << c.zoom);
if (x < 0) {
x = x + (1 << c.zoom)
}
// Set Y to numTiles - c.row, to account for TMS doing lat backwards
var y = (1 << c.zoom) - c.row - 1;
var url = "http://example.com/tiles/" + c.zoom + "/" + y + "/" + x + ".jpg";
Below is the result of my map experiments: the track of a flight with Ken flying practice approaches at Salinas overlayed on top of two approach charts and the Google Terrain base layer. It’s a bit of a jumble.
Transparent brown line: flight track
Black scratchy lines: approach chart
Brown terrain contours: approach chart
Green terrain: Google maps
What I’m really trying to highlight is the juxtaposition of the GPS track to the black approach path on the procedure plate. The other stuff is context, or noise. It’s less confusing if you only draw one approach chart, not two. Making parts of the approach plate transparent is a big help too; it’d be nice to eliminate the terrain, etc entirely. Maybe just let the black lines come through.
I updated Quantum GIS to 1.6.0. It claims some improvements for georeferencing. I also learned better how it works.
Transformation Types are documented in the Quantum GIS manual. The docs suggest Polynomial 3 or Helmert are the best choices. Polynomial 3 is a nonstarter since it requires at least 10 GCPs and Helmert produced an oddly rotated image that was not correct. Linear, Polynomial 1, Projective, and Thin Plate Spline all produced very similar results. Linear isn’t even a proper transform, really, but it seems close enough for my purposes. I’m shooting in the dark here, not knowing how the source NACO plates are projected, but at this scale and for my purposes any errors are not too big a deal.
The Target SRS you set in the Georeferencer is just an annotation, it doesn’t magically cause some warping. I’d tried setting it to EPSG:900913 for the Google (scale: 1 = 1m or something) but was typing latitude and longitudes in the tool (scale: 1 = 1 degree). Works better if I set the Target SRS to EPSG:4326 for WGS 84, produce a GeoTIFF, then later warp the image to Google mercator.
Raster / Warp will let you do the warping to Google. All it’s doing is calling gdalwarp, something like gdalwarp -s_srs EPSG:4326 -t_srs EPSG:900913 -r cubicspline -of GTiff input.tif output.tif. I wonder if this is really even warping anything or it’s just rescaling?
Bottom line:
Draw 4 or so georeferencing control points on the chart. Type latitude and longitude.
Set Transformation Settings to Polynomial 1, Cubic Spline, LZW, EPSG:4326.
QGIS has a bunch of Raster tools where it calls GDAL. GDAL invocations were failing. I think I tracked it down with help from the IRC channel: it wasn’t finding the GDAL binary path. Setting it in the Settings makes stuff work. Details at http://trac.osgeo.org/qgis/ticket/3476
I’m taking a crack at quick and dirty geo-referencing of NACO approach plates for pilots. They come as PDF images, ungeoreferenced, but they contain points with precise latitude and longitude you can align by hand. The result won’t be accurate, certainly not for navigation, but maybe it’s good enough. Here’s some notes on what I’ve tried.
Convert it to PNG via pdftoppm -r 300 | pnmtopng -comp 9. The result file will be 1613x2476, about 700k.
Fire up Quantum GIS (I’m using 1.5.0). Launch Plugins/Georeferencer/Georeferencer.
File /Open Raster to load your PNG.
Zoom in and add some georeference points via Edit / Add Point. I picked a few intermediate GPS fixes on a GPS approach and looked up their coordinates via fltplan.com. Don’t forget that X is longitude, and is negative. How many points? 2 is minimum, I entered 4. It all depends on what projection the NACO plates uses, and I don’t know what that is.
File / Save GCP Points, to save your hand edited work.
Settings / Transformation Settings. Lots of options I don’t understand. Target SRS is EPSG:4326 for WGS84. LZW compression gets the filesize from 12 megs to 2 megs.
Look at the table of points below the view of your map. The last 3 columns (dX, dY, residual) are some sort of measurement of the error / warping requirements.
File / Start georeferencing to generate the georeferenced TIFF output. Takes a few seconds.
gdalinfo on the resulting .tif file to see whether the result looks reasonable.
Close the georeferencer plugin.
Start a new Quantum GIS project. Settings / Project Properties to set the CRS to EPSG:4326.
Layer / Add Raster Layer to load the georeferenced TIFF. It should show up in the window, with coordinates of lat/long and a scale in the vicinity of 1:300,000.
Add more layers to juxtapose other data on top of the georeferenced plate. State boundaries are helpful for getting oriented, I also overlayed a GPS flight track.
The NACO plate background is RGB 236, 236, 236. You can make that transparent with the Transparency properties of the plate layer, adding a band for just that one RGB value with 100% transparent.
One thing I haven’t figured out how to do in Quantum GIS is draw my plates on top of some reasonable map, like Google terrain maps. I can load Google maps via the OpenLayers plugin but the coordinate system those maps use is something screwy with X/Y in the hundreds of thousands. I’m not even sure Quantum GIS will warp raster layers on the fly, nor have I figured out what target SRS I should be emitting to be in the same format.
My real goal is to end up loading this stuff in Javascript, with Polymaps.
I got a Spot for Christmas. In addition to emergency use they have a tracking option where it records your position via satellite every 10 minutes, live. The website is awful and they don’t keep your data very long, but the data is there. And they have an API of sorts. Related search: [findmespot completexml]. Some notes:
Data comes in a custom XML format. It’s pretty simple, each message is an XML blob with a latitude, longitude, and timestamp (in some random timezone!). Also some other junk.
The data is cached and only updated every 15 minutes. I’ve been told there’s more latency than that.
The shared page only shows data for the last 7 days.
Spot keeps your data for only 30 days. There’s also a manual download option.
Spot has a fancy site for hosting trip diaries at http://www.spotadventures.com. It includes KML and GPX downloads, photos, notes, etc. It looks like a pretty complex and featureful product with very few users.
I haven’t found any sort of hacker community for Spot. There is at least one third party service, though: Spotwalla.
Sort of related: Spot’s new system includes a “Type & Send” feature where you can send arbitrary 41 character messages via the satellite network. They charge $0.10/message in bulk.
I want short names to refer to a specific latitude/longitude. Mostly so I can type them easily into an aviation GPS. For my purposes I need accuracy of about 1 mile, so 1 minute or .01 degree. I only need coordinates valid in the continental US, bounded roughly by 20, -125 to 50, -65. Some options, with the encoding for San Francisco (roughly at 37.75, -122.34).
377512243. Lat/long base 10. 9 characters per location, and dead-ass easy to understand.
9q8yvv. Geohash, a hierarchical base 32 encoding. 6 characters per location. See here for visualization.
KO46D. “Grid Fixes” from FltPlan. 5 characters per location. Can’t find documentation but it seems to have a resolution of 10 minutes latitude, 1 degree longitude. Not really accurate enough.
CM87SR. 6 characters per location. Grid Squares, aka Maidenhead Locator System, a ham radio thing, here’s a map view. Accurate to 2.5′ latitude and 5′ longitude, or roughly 4 miles, so not good enough for my purposes. There is an 8 character extended locator option.
?????. Perfect rectangular coding, base 32. 5 characters per location. Need (50-20)*60 = 1800 = 11 bits of latitude, and (125-65)*60 = 3600 = 12 bits of longitude. 23 bits can be encoded in 5 characters in a base 32 representation. A base 52 representation would get it down to 4 characters.
I think if I were actually building this I’d probably go for Geohash. It has a nice property that you can specify arbitrary precision, then lop characters off the right to make a shorter code that’s less specific.
Let’s say I make some great SRTM altitude tiles, where can I host them that I don’t go broke? Map tiles are funny, they’re just static files so you don’t need a big server, just cheap bandwidth. I did a quick look around at some options:
Amazon S3 / CDN: $150/mo = 1TB, no server
Google AppEngine: $120/mo = 1TB. Limitations may make it impossible.
oneandone.net: $150/mo = 3TB with a server. SkyVector is here.
godaddy: $135/mo = 1.5TB with a server. Used by PDFPlates? NACOmatic was serving 20TB / month for awhile, not sure how that worked out
Voxel: $100/mo = 1TB. FlightAware is here.
one guy I know uses GoDaddy, hostgator, justhost, and linode to push about 2TB / month. HostGator supposedly cut him off without notification at some point.
I heard ReadyHosting shut down a 20 TB / month project
random “unmetered” hosting: the challenge is to find the one that’s actually unmetered and doesn’t have hidden throttles or termination policies.
I don’t know much about hosting. Static map tiles are a weird kind of thing to host.
Update: chunkhost offers $66/mo = 3.2TB with a decent Xen slice.
Now that I have sample tiles from my SRTM data, what format do I want to store them in?
An 8 bit paletted image is sufficient. I really only need 2 colours: transparent (below 8000′) and white (above 8000′). All the other colouring is just so it looks nice. (May save space using 64 or 128 colours). Even GIF would work, but I think PNG-8 (color type 3) is a better choice. Interestingly, even palettized PNGs support a full alpha channel for all 256 colours, see the tRNS chunk.
Do all the tiles need to have the same palette? They can, since it’s the same colormap for all the images. Not sure how to convince GDAL / other tools to reuse the palette, though, particularly with the transparency data. I’m guessing I’m going to need a post-processing step after GDAL generates the final slippy map tiles. Maybe that final PNG baking step is the time to enforce a single palette. The other processing I want to do is optimize via one of pngslim pngnq pngcrush optipng advpng. A quick test shows optipng saves 50%, I think by translating 24+8 bit images to 8 bit paletted images. I swear I saw a map hacker’s notes on comparing these tools once.
One related idea I’ve had for awhile: it’d be awesome to make a set of SRTM tiles that were a simple greyscale, 0-255, and then remap them to full colour + transparency in Javascript, in the client. That way the user could quickly choose what altitudes to highlight. I think it’s barely possible using the canvas API, not sure if it’s a good idea.
Working on a static render of my SRTM tiles. Decided to use gdaldem to do the color mapping, it does all I need.
First I needed gdal 1.7 to use gdaldem, but Debian still packages older versions. There’s a lot of instructions for compiling. Long story short, ./configure; make works fine. It’s 1 million lines of code, so I had a nice cup of coffee.
Here’s how to use gdaldem to turn an SRTM .hgt file into a PNG: gdaldem color-relief -alpha -of png N39W120.hgt nelson.cmap gdaldem.png. There’s a variety of color map options, I hand-coded my own:
That maps everything from 0-2437 meters (8000′) to transparent, then a grey ramp up to 10000′, then a red ramp up to 15000′, then solid red. Missing values (NV) are coloured green; need to deal with them later. The result looks like this
Now a bit of shell scripting to run the whole set:
for f in *.hgt; do
../experiment/gdaldem color-relief -alpha -of png $f ../png/nelson.cmap ../png/${f%.hgt}.png;
done
It’s awfully fast, I’m impressed with GDAL speed. The output PNG isn’t so bad, either, the empty tiles end up being 2k or so each.
Next up: gdal2tiles.py to turn these into tiles I can serve for a slippy map. I might need to gdalbuildvrt first to combine all the files into one big virtual map.
I took a quick trip through this gdal tutorial on raster data, albeit with SRTM data instead of the example data. Things I learned:
gdalinfo has useful flags for finding min/max values, stats, etc.
gdal_translate is how you render a dataset to an image gdal_translate -ot byte -scale 1152 3184 -of PNG N39W120.hgt test.png
Input range doesn’t seem to autoscale, despite what the docs say. Haven’t figured out how to apply a custom colormap yet. (The FAQ is discouraging, but gdaldem color-relief might do what I need.) The PNG output from GDAL doesn’t seem to have any geodata stored in PNG chunks.
gdalwarp is how you reproject data
gdal_merge is how you mosaic images. You can use gdalwarp to do it, too, but it’s overkill. gdalwarp N39W120.hgt N39W121.hgt N38W120.hgt N38W121.hgt big.tiff
gdal_translate -outsize 50% 50% -scale 1000 3000 -of PNG big.tiff test.png
gdal_rasterize lets you render vector data (via OGR) into raster data
gdaladdo creates downsampled overviews for data, for faster access. In my previous experiments the overviews didn’t make mapserver any faster on my SRTM data.
gdal has virtual formats which are a text file that describes multiple raster files as a single dataset. mapserver uses something different to accomplish this, a shapefile.
No hacking today, went flying instead. Ended up being a passenger the whole 3 hour flight, crappy IFR weather. But as always I captured the flight on my little AMOD GPS tracker and mapped the track through my custom GPS track mapper project. The result is quite surprising; not only is data missing, but the track is wrong! In particular when we left Modesto we did not fly south, we flew more or less west, and the GPS recorded the wrong position. What happened?
My GPS tracker logs NMEA sentences once a second and records all sorts of neat data. Unfortunately I’m not graphing it yet, so I turned instead to GPS visualizer to visualize some auxilliary data: specifically the # of satellites we had for the fix as well as the horizontal dilution of precision, a measure of fix accuracy.
As you can see in the graph, the HDOP spiked really high for about 10 minutes around 23:20, or exactly when my position data was bad and then disappeared. I’d naively assumed the GPS tracker wouldn’t even record data if it didn’t have a good fix. Apparently it does. The Wikipedia article suggests I should be ignoring fixes with HDOP > 10 or so. My tracker also records vertical DOP; in general GPS isn’t as good at vertical position as horizontal, so that data may be even worse.
One other graph: # of satellites as a function of HDOP. My GPS apparently needs to see 5 satellites to give an accurate position. No idea if that’s true for all GPS chipsets (I think 4 is minimal), but this tracker uses the decent SiFR III chipset so I imagine it’s doing about as good as it can.
I’ve got a long list of things to do with my GPS track mapping program. I hope to make it a web site for others to use some day.
Awhile back I made a slippy map of parts of the US over 8000′. I did it using SRTM elevation data turned into images with mapserver, a dynamic program. Easy to get going but awfully slow to serve. I’d like to make the same map but statically. Inspired by Matt’s success with gdal2tiles.py I thought I’d try again.
My source data is the .hgt files for North America. They’re bundled together into a single index.shp file using gdaltindex, as described in the mapserver docs. A quick and dirty render is accomplished with
That does all the expected tiling and rendering at multiple scales, but doesn’t have a meaningful colourmap. But in my work with Mapserver I created a meaningful colormap:
For each input point from SRTM, map the range 2438:4572 to 0:255.
This maps everything < 8000′ to 0, everything over 15000′ to 255, and a linear range between.
Map the input band “1” (the altitude) to the output channels RGBA. Ie, a full 32 bit image with 8 bits of alpha.
LUT_4 maps everything that is 0 (< 8000′) to transparent, everything > 0 to fully visible (alpha = 255)
LUT_1-3 apply a colourmap. 1 (8000′) is mapped to 0,0,0 (black), 73 (10000′?) maps to 80,80,80 (grey), and 255 (15000′) maps to red. This gives a color ramp: black to grey to red.
Now I need to figure out how to generate the same colourmap using solely GDAL. And then convince gdal2tiles to do that colourmapping, probably by first turning my HGT files into GeoTIFF and then tiling the GeoTIFF.
Now that I have GeoDjango up and running I was able to import a bunch of airport data using Adam’s code. Back to PostGIS to play!
select facility_name,
floor(ST_Distance_Sphere(point,
ST_GeomFromText('POINT(-122.4522 37.7555)')))
as distance
from airports_airport
where control_tower = true
order by distance
limit 10;
ERROR: geometry_distance_spheroid: Operation on two GEOMETRIES with different SRIDs
Frowny. Face. What’s that mean?
Long story short, an SRID identifies which Spatial Reference System the coordinates are with reference to. It’s a bit like units: it’s not enough to say something “weighs 100”, you have to specifiy if you mean 100 lbs, or 100 kgs, or whatever. For more theoretical background, see Geodesy. There’s a giant database of SRIDs at http://spatialreference.org/. (Related keyword: EPSG). Greatest hits:
4326: WGS 84, the reference most GPSes use. I think many people assume this is the SRID by default.
GeoDjango defaults to SRID 4326; you can use others, details here. PostGIS ST_GeomFromText defaults to an SRID of -1, which I guess means unknown. But if you’re explicit then it works fine. You can also use PostGIS to transform from one SRID to another, I believe underneath it uses PROJ.4
Personally I find this all frustrating; can’t we just use WGS 84 everywhere and be done with it? Sure, you still need to project when rendering a flat map, but consider that a separate thing entirely.
Fun fact: the reference points for WGS 84 move. And are remeasured roughly yearly. Apparently Greenwich is not at 0 longitude in WGS 84.
Today’s hacking project is getting up to speed with modern GIS. Specifically, PostGIS (Postgres with spatial features) as a database, QGis as a graphical frontend for viewing graphics data, and GeoDjango for building webapps.
QGis is awesome: you can quickly add layers, including layers that come from PostGIS. Loaded layers are on the tray to the left, you can right click them to set display options, enable a query to filter what’s displayed, etc. There’s also an edit mode for editing geometry.
PostGIS is encouraging. Some notes:
Tutorial: Getting to know PostGIS has you setting up the database in part 1, then inserting useful shapefile data in part 2. Some of the details are out of date.
Manual: Create a spatially-enabled database tells you the extra incantations required to add GIS capability to a Postgres database. It’s a little funky, you have to enable PL/pgSQL language and then load some predefined functions.
After finishing all the setup I loaded the cities and counties file referenced in that first tutorial (at USGS) It was easy to load them up into QGis for display. “Show me county outlines, and the names and locations of all cities with more than 100,000 residents”.
Playing in PostGIS, here’s some interesting queries:
select county, ST_Area(wkb_geometry) as area from us_counties
where state = 'CA' order by area desc limit 5;
Biggest county. Units of Area are.. degrees?
county | area
----------------------------------------------------+------------------
San Bernardino County | 5.13534296766738
Inyo County | 2.66716021408502
Kern County | 2.09407653001836
Riverside County | 1.84319135357509
Siskiyou County | 1.77534424474288
select county, ST_AsText(ST_Simplify(wkb_geometry, 0.1))
from us_counties where state = 'CA' limit 1;
(returns a simplified polygon of the county outline)
\d us_counties
shows all the columns. The interesting one is
wkb_geometry | geometry
Geometry is a polymorphic type, in the case of this shapefile it's a Polygon. The "WKB"
name is just a descriptive, but implies the import source was in "well known binary" format.
select name, ST_X(wkb_geometry), ST_Y(wkb_geometry)
from us_cities where name like 'San %' and state = 'CA';
San Anselmo | -122.561653137207 | 37.9746437072754
San Rafael | -122.531089782715 | 37.9735336303711
San Quentin | -122.487464904785 | 37.9412689208984
select name, state,
floor(ST_Distance_Sphere(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'))) as distance_from_SF
from us_cities where state='CA' order by distance_from_sf limit 5;
name | state | distance_from_sf
--------------------------------------------------+-------+------------------
San Francisco | CA | 3602
Daly City | CA | 5596
Broadmoor | CA | 8207
Colma | CA | 8767
Brisbane | CA | 9495
select county from us_counties where
ST_Contains(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'));
shows which county contains an arbitrary lat/lon
select county, ST_Area(wkb_geometry) as area from us_counties where state = 'CA' order by area desc limit 5;
I’ve been working with Adam Fast to build a Python library to parse FADDS data. FADDS data is a US aviation database from the FAA, it contains things like locations of airports, nav fixes, etc. The primary branch is at https://github.com/adamfast/faddsdata, my fork is at https://github.com/NelsonMinar/faddsdata. So far we’re parsing two of the files (APT.txt and NATFIX.txt), adding new files is pretty easy.