Skip to content

Instantly share code, notes, and snippets.

@nikmolnar
Last active March 17, 2016 15:56
Show Gist options
  • Save nikmolnar/8fe7ae487ad74fdf2984 to your computer and use it in GitHub Desktop.
Save nikmolnar/8fe7ae487ad74fdf2984 to your computer and use it in GitHub Desktop.
Simple example of rendering a GeoTIFF using the mapnik RasterSymbolizer
import mapnik
m = mapnik.Map(600, 600)
m.srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
rs = mapnik.RasterSymbolizer()
# COLORIZER_DISCRETE is a binned/classified rendere. Other options are COLORIZER_LINEAR (stretched) and
# COLORIZER_EXACT (unique)
rs.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(0, 0, 0, 0))
rs.colorizer.add_stop(-417, mapnik.Color(0, 0, 0))
rs.colorizer.add_stop(68, mapnik.Color(255, 255, 255))
rs.colorizer.add_stop(234, mapnik.Color(255, 0, 0))
rs.colorizer.add_stop(461, mapnik.Color(0, 0, 255))
rs.colorizer.add_stop(719, mapnik.Color(0, 255, 0))
s = mapnik.Style()
r = mapnik.Rule()
r.symbols.append(rs)
s.rules.append(r)
m.append_style('Default', s)
# Load the GeoTIFF via GDAL. I think there's a standalone plugin as well, but I had problems with it
ds = mapnik.Gdal(file='data.tif', band=1) # band=1 is important. Omitting it results in strange render behavior
layer = mapnik.Layer('layer')
# Layer SRS is NOT loaded automatically
layer.srs = '+proj=lcc +lat_1=49 +lat_2=77 +lat_0 +lon_0=-95 +x_0=0 +y_0=0'
layer.datasource = ds
layer.styles.append('Default')
m.layers.append(layer)
# Zoom to full extent, could also set a specific extent with
# m.zoom_to_box(mapnik.Box2d(-4500000, -4500000, 4500000, 4500000))
m.zoom_all()
mapnik.render_to_file(m, 'render.png', 'png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment