User:Moresby/Understanding Mapnik/Specifying line styles

From OpenStreetMap Wiki
Jump to: navigation, search
Understanding Mapnik
A Mapnik tutorial
Starting with Python
Using XML and CSS
CartoCSS and PostGIS
032-lines-stroke.png - roads shown with dashed lines

By using a Mapnik Stroke object, we can configure more details of our lines than just the colour and width. Here we use the dasharray attribute of the Stroke object to specify how we want our dashed lines to be drawn.

 1 #!/usr/bin/python
 2 
 3 # Load the Python mapnik libraries.
 4 import mapnik
 5 
 6 # Create a new map.
 7 m = mapnik.Map(480, 320)
 8 
 9 # Set the background colour.
10 m.background = mapnik.Color('ghostwhite')
11 
12 # Create a stroke object.
13 stroke = mapnik.Stroke()
14 stroke.color = mapnik.Color('green')
15 stroke.dasharray = [ (6, 2) ]
16 stroke.width = 2
17 
18 # Create a line symbolizer.
19 line_symbolizer = mapnik.LineSymbolizer(stroke)
20 
21 # Create a new rule and add the symbolizer.
22 r = mapnik.Rule()
23 r.symbols.append(line_symbolizer)
24 
25 # Create a new style and add the rule.
26 s = mapnik.Style()
27 s.rules.append(r)
28 
29 # Add the style to the map.
30 m.append_style('basic_style', s)
31 
32 # Specify that our data is coming from a CSV file called "data-roads.csv".
33 ds = mapnik.CSV(file='data-roads.csv')
34 
35 # Create a new layer for the map, called "main_map" and add the data
36 #   source and style to that layer.
37 l = mapnik.Layer('main_map')
38 l.datasource = ds
39 l.styles.append('basic_style')
40 
41 # Add the layer to the map.
42 m.layers.append(l)
43 
44 # Zoom to the part of the map we are interested in.
45 m.zoom_to_box(mapnik.Box2d(0, 0, 480, 320))
46 
47 # Save the map as a PNG image.
48 mapnik.render_to_file(m, '032-lines-stroke.png', 'png')

Save this program in a file called 032-lines-stroke.py and run it by typing:

python 032-lines-stroke.py

You should see no error messages, and you should see a new file in your working directory called 032-lines-stroke.png. This is a new map image, and should be a light-coloured rectangle 480 pixels wide by 320 pixels high, with a series of interconnected dashed green lines, as shown above.