User:Moresby/Understanding Mapnik/Plotting points

From OpenStreetMap Wiki
Jump to: navigation, search
Understanding Mapnik
A Mapnik tutorial
Starting with Python
Using XML and CSS
CartoCSS and PostGIS
020-points.png - some points plotted

The first actual content we will put on our map is a collection of points. Here is the program do to that:

 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 point symbolizer.
13 point_symbolizer = mapnik.PointSymbolizer()
14 
15 # Create a new rule and add the symbolizer.
16 r = mapnik.Rule()
17 r.symbols.append(point_symbolizer)
18 
19 # Create a new style and add the rule.
20 s = mapnik.Style()
21 s.rules.append(r)
22 
23 # Add the style to the map.
24 m.append_style('basic_style', s)
25 
26 # Specify that our data is coming from a CSV file called "data-places.csv".
27 ds = mapnik.CSV(file='data-places.csv')
28 
29 # Create a new layer for the map, called "main_map" and add the data
30 #   source and style to that layer.
31 l = mapnik.Layer('main_map')
32 l.datasource = ds
33 l.styles.append('basic_style')
34 
35 # Add the layer to the map.
36 m.layers.append(l)
37 
38 # Zoom to the part of the map we are interested in.
39 m.zoom_to_box(mapnik.Box2d(0, 0, 480, 320))
40 
41 # Save the map as a PNG image.
42 mapnik.render_to_file(m, '020-points.png', 'png')

We also need to have some data to plot. The following data are some coordinates for some towns and cities in the United Kingdom. For now, don't worry too much about what the coordinates mean, just that they represent the locations on the map we want to create. Save the following lines in a file called data-places.csv:

name,              type,       x,   y

"Bedford",         town,      48,  93
"Bury St Edmunds", town,     398, 147
"Cambridge",       city,     221, 125
"Ely",             city,     263, 222
"Harlow",          town,     220, -81
"Huntingdon",      town,     131, 188
"Kettering",       town,     -29, 222
"Letchworth",      town,     119,  17
"March",           town,     213, 297
"Newmarket",       town,     307, 146
"Peterborough",    city,     113, 308
"Royston",         town,     179,  51
"Saffron Walden",  town,     259,  39
"Sherington",      town,     -22,  79
"St Ives",         town,     164, 190
"St Neots",        town,     108, 133
"Stowmarket",      town,     483, 119
"Thetford",        town,     409, 231

Save this program in a file called 020-points.py and run it by typing:

python 020-points.py

You should see no error messages, and you should see a new file in your working directory called 020-points.png. This is a new map image, and should be a light-coloured rectangle 480 pixels wide by 320 pixels high, with some small black squares marking the positions of the items in the data file, as shown above.