A Mapnik tutorial
Starting with Python
Using XML and CSS
CartoCSS and PostGIS
060-text.png - towns, cities, roads and motorways marked, labelled with text
Placing text on a map can be a complicated process. Here we look at the basics, putting labels on our places and roads.
3 # Load the Python mapnik libraries.
4 import mapnik
6 # Create a new map.
7 m = mapnik.Map(480, 320)
9 # Set the background colour.
10 m.background = mapnik.Color('ghostwhite')
12 # Create a stroke object for railways.
13 stroke_rail = mapnik.Stroke()
14 stroke_rail.color = mapnik.Color('black')
15 stroke_rail.dasharray = [ (6, 2) ]
16 stroke_rail.width = 2
18 # Create point, line and text symbolizers.
19 point_symbolizer_city = mapnik.PointSymbolizer(mapnik.PathExpression('circle_red_16x16.png'))
20 point_symbolizer_town = mapnik.PointSymbolizer(mapnik.PathExpression('circle_red_8x8.png'))
21 line_symbolizer_rail = mapnik.LineSymbolizer(stroke_rail)
22 line_symbolizer_road = mapnik.LineSymbolizer()
23 line_symbolizer_mainroad = mapnik.LineSymbolizer(mapnik.Color('black'), 2)
24 line_symbolizer_motorway = mapnik.LineSymbolizer(mapnik.Color('lightblue'), 4)
26 text_symbolizer_roads = mapnik.TextSymbolizer()
27 text_symbolizer_roads.name = '[name]'
28 text_symbolizer_roads.face_name = 'DejaVu Sans Book'
29 text_symbolizer_roads.halo_radius = 2
30 text_symbolizer_roads.label_placement = mapnik.label_placement.line
32 text_symbolizer_towns = mapnik.TextSymbolizer()
33 text_symbolizer_towns.name = '[name]'
34 text_symbolizer_towns.face_name = 'DejaVu Sans Book'
35 text_symbolizer_towns.halo_radius = 3
36 text_symbolizer_towns.displacement = (0, 7)
38 text_symbolizer_cities = mapnik.TextSymbolizer()
39 text_symbolizer_cities.name = '[name]'
40 text_symbolizer_cities.face_name = 'DejaVu Sans Book'
41 text_symbolizer_cities.halo_radius = 3
42 text_symbolizer_cities.displacement = (0, 11)
43 text_symbolizer_cities.fill = mapnik.Color('red')
44 text_symbolizer_cities.text_size = 12
46 # Create new rules and add the symbolizers.
47 r_city = mapnik.Rule()
50 r_city.filter = mapnik.Filter('[type] = "city"')
52 r_town = mapnik.Rule()
55 r_town.filter = mapnik.Filter('[type] = "town"')
57 r_rail = mapnik.Rule()
59 r_rail.filter = mapnik.Filter('[type] = "rail"')
61 r_road = mapnik.Rule()
64 r_road.filter = mapnik.Filter('[type] = "road"')
66 r_mainroad = mapnik.Rule()
69 r_mainroad.filter = mapnik.Filter('[type] = "mainroad"')
71 r_motorway = mapnik.Rule()
74 r_motorway.filter = mapnik.Filter('[type] = "motorway"')
76 # Create new styles and add the rules.
77 s_point = mapnik.Style()
81 s_line = mapnik.Style()
87 # Add the styles to the map.
88 m.append_style('point_style', s_point)
89 m.append_style('line_style', s_line)
91 # Specify our data sources.
92 ds_point = mapnik.CSV(file='data-places.csv')
93 ds_line = mapnik.CSV(file='data-roads.csv')
95 # Create new layers for the map, add the data sources and styles to
96 # those layers.
97 l_point = mapnik.Layer('point_layer')
98 l_point.datasource = ds_point
100 l_line = mapnik.Layer('line_layer')
101 l_line.datasource = ds_line
104 # Add the layers to the map. We want the points to appear in front of the
105 # lines, so we add the line layer first.
109 # Zoom to the part of the map we are interested in.
110 m.zoom_to_box(mapnik.Box2d(0, 0, 480, 320))
112 # Save the map as a PNG image.
113 mapnik.render_to_file(m, '060-text.png', 'png')
Detailed explanation of this program
- In this example we use a new type of symbolizer: the TextSymbolizer. This places text at points or along lines. We create three symbolizers: one for towns, one for cities and one for roads. Creating and configuring the TextSymbolizer objects takes place between lines 26 and 44.
- For each symbolizer, we set the
name attribute. This specifies an expression which provides the text we want to place on the map. For our data, we want the text in the "name" field to be printed for the towns, cities and roads. The expression
[name] produces the value of that field, in the same way that
[type] represents the field "type" in our rule filters. These attributes are set at lines 27, 33 and 39.
face_name attribute for the symbolizers specifies the name of the font to be used for the text. We choose "DejaVu Sans Book" which should already be installed on your system as part of the Mapnik dependencies. To list the fonts available, type:
python -c "from mapnik import FontEngine as e;print '\n'.join(e.instance().face_names())"
- The following fonts should be available on all systems:
- DejaVu Sans Bold
- DejaVu Sans Bold Oblique
- DejaVu Sans Book
- DejaVu Sans Condensed
- DejaVu Sans Condensed Bold
- DejaVu Sans Condensed Bold Oblique
- DejaVu Sans Condensed Oblique
- DejaVu Sans ExtraLight
- DejaVu Sans Mono Bold
- DejaVu Sans Mono Bold Oblique
- DejaVu Sans Mono Book
- DejaVu Sans Mono Oblique
- DejaVu Sans Oblique
- DejaVu Serif Bold
- DejaVu Serif Bold Italic
- DejaVu Serif Book
- DejaVu Serif Condensed
- DejaVu Serif Condensed Bold
- DejaVu Serif Condensed Bold Italic
- DejaVu Serif Condensed Italic
- DejaVu Serif Italic
- When putting text onto a map, it can sometimes be difficult to read if there are other map features nearby. By setting the
halo_radius attribute, we can get the symbolizer to add a small ring of space around the text, visually separating it from anything else present. We set this to two pixels of space around the road names, and three pixels around the place names. We set these values at lines 29, 35 and 41. The effect can be seen in several places on the map, including at the end of the text "Bury St Edmunds" where a small amount of road is removed to ensure the text is readable.
text_size attribute allows us to specify the size of the text. For our city labels, we want a slightly larger text size than normal, so we specify a height of twelve pixels (points?) at line 44. For the other labels, the default of ten pixels (points?) will be fine.
fill attribute controls the way in which the text is painted. For our city labels, we choose the colour red at line 43. The default of black will be fine for the other labels.
- By default, a TextSymbolizer places text centrally over a point (or the middle of a line). For our town and city labels, we want them moved slightly downwards so that they don't attempt to occupy the same space as the red circles. The
displacement allows us to specify where the text is to be placed relative to the point in question. For cities, we set a displacement of
(0, 11) at line 42, meaning that the text label will be moved 11 pixels lower than it would be otherwise. For towns, which have a smaller circle, we set a slightly smaller displacement of
(0, 7) at line 36.
label_placement attribute of the TextSymbolizer allows to to specify how a label is drawn on a line. By default, the label is placed at the midpoint of the line, oriented horizontally. We set the value to
mapnik.label_placement.line at line 30 to tell Mapnik to orient the label along the road instead.
- Looking at the output, we start to see some of the results of the way in items are added to the map. Mapnik keeps track of where it has placed items on the map, and will not attempt to place further items which overlap with those already placed.
- From the previous example, we expect to see a large red circle at Cambridge, but it is missing on this image. This is because the label for the A14 is placed exactly halfway along the road, and by chance ends up just where we would expect the red circle to be. When Mapnik comes to put the red circle in its place, the A14 label is therefore obstructing it, so the circle doesn't get drawn. This is also the case for Newmarket and the label for the A11. We could, of course, arrange for the circles to be drawn first, ensuring that there is nothing in their way, but with our current setup, this would mean that the roads get drawn on top of the red circles, which is not what we want.
- Similarly, a few of the towns have a small red circle, but no label, for the same reason: St Ives, St Neots, Bedford and Royston.
- Although the halo around the Bury St Edmunds label prevents the text from colliding with the road, the halos for the road names sometimes appear less effective. In particular, the A1198 label is placed on top of the A428, making it difficult to read. Similarly, the A605 label conflicts with the railway.
- These are the sorts of problems which Mapnik can largely be avoided by more in-depth definition of Mapnik styles and rules. However, what we have achieved so far is a pretty good start.
Save this program in a file called
060-text.py and run it by typing:
You should see no error messages, and you should see a new file in your working directory called 060-text.png. This is a new map image, and should be a light-coloured rectangle 480 pixels wide by 320 pixels high, with towns, cities and roads labelled with text, as shown above.