Banner

Wednesday, 25 July 2012

Creating contour lines with GDAL and Mapnik

Credits: Wikipedia
So far we’ve used our Digital Elevation Model (DEM) to create hillshade and color relief. Contours is another common cartographic method used to show the shape of the terrain. If contour lines are placed close to each other, it means that the terrain is steep. Let’s add some contours for our terrain map of Jotunheimen.

We can use a GDAL command, gdal_contour, to create vector contour lines from a DEM:

gdal_contour -a height jotunheimen.tif jotunheimen_contour_25m.shp -i 25.0

The resulting shapefile has an attribute named “height” (-a) containing the elevation of each contour line. The contour interval, the difference in elevation between successive contour lines, is 25 meters (-i).

Let's render the contour lines with Mapnik (jotunheimen_contours.xml):


We can use Nik2Img to create an image from the Mapnik XML file:

nik2img.py jotunheimen_contours.xml jotunheimen_contours.png -d 4096 4096 --projected-extent 460000 6810000 470000 6820000

Contour lines for Besseggen mountain ridge

I want to render the contour lines differently for various zoom levels. The contours should be more visible at higher zoom levels, and we should add numbers showing the actual elevation for some of the contours. I also want to make the contour lines for every 100 meters thicker. To achieve this we need to know the map scale at different zoom levels. In the last blog post, we calculated the resolution (meters per pixel) for each zoom level. You get the map scale by dividing this number by 0.00028 (234.375 / 0.00028 = 837053.571).

Zoom
Resolution
Scale
0
234.375
837054
1
117.1875
418527
2
58.59375
209263
3
29.296875
104632
4
14.6484375
52316

For zoom level 4, the map scale is about 1:50,000. Read more about map scale on this excellent Mapnik page

Let’s create a style rule that will display the elevation on a contour line on zoom level 3:

If you look at the table above, the only scale number between the max and min scale denominator is 104632, which corresponds to zoom level 3. jotunheimen_contours2.xml includes all the style rules to render the contour lines differently for five zoom levels. You’ll also see that I’ve created contour shapefiles with contour intervals of 25, 100, 200 and 500 meters, - to be able to render these differently.

Finally, I've used TileCache to render transparent tiles with contours, and added them as a separate layer to Leaflet map:


Fullscreen map

1 comment:

Lars Johansson said...

Very nice tutorial Bjørn!
I am trying adding labels based on the datasets form kartverket, "Stedsnavn SSR, WGS84, geoJSON".
Trying a shapefle conversion using
ogr2ogr -skipfailures -f "ESRI Shapefile" shapefiles/myshape.shp kildefiler/kartverket/stedsnavn.geojson -s_srs EPSG:4326 -t_srs EPSG:32633
but obviously there is some projection errors (my guess) as the layers won't align.

Considering an example perhaps? :)