Map Rendering
How to Use the Mapnik Engine to Generate Map Imagery
Mapnik - The Map Renderer
What is Mapnik?
Mapnik is a tool to render geo-spatial information into an
image.
When composing the final image, Mapnik fetches the relevant geo-spatial information from various
sources.
It then re-projects them and composes them into a layered
image.
-
Data Sources
Data sources can include vector and raster files.
This includes geospatial databases. When accessing the database, you can define arbitrary queries to filter your data. -
Styles
Mapnik lets you define styles for each layer of your composition. The styles determine how the geometries appear in the final image. Styles include different colors for line and polygon strokes as well as fill colors and gradients for polygons.
You can also define repeating patterns for fill styles as well as a compound of different styles.
Text symbolizers enable you to draw text label in your map image.
Image Composition from Layers
The final map shows the Dubai Metro lines running through Dubai. The final image is a composition of different layers drawn atop each other.
Calling Mapnik from Node.js
const mapnik = require("mapnik");
const fs = require("fs");
mapnik.register_default_fonts();
mapnik.register_default_input_plugins();
// create the map object
const map = new mapnik.Map(1000, 1000);
// load map definition, layers and styles
map.load("./map-styles.xml", function(err, map) {
// any invalid style file will create an error
if (err) {
console.error(err);
process.exit(1);
}
// move the map to the max extent defined in the styles
map.zoomAll();
// render an image
const im = new mapnik.Image(1000, 1000);
map.render(im, function(err, im) {
// create a PNG
im.encode("png", function(err, buffer) {
// write the file from the buffer
fs.writeFileSync("map-image.png", buffer);
});
});
});
Mapink offers APIs for C++, Python and Node.js. All are based on the C++ API. Thus, naming and functionality is common across all APIs.
The npm package mapnik is required to use Mapnik in Node.js.
The sources, layers and styles of the map are defined in the map definition xml.
Defining Styles in Code
It is possible to define the map, layers and styles in code using the mapnik API. However, keeping these definitions in the XML improves modularity and the styling process.
Create Map Web Service with Express and Node.js
You can create a map service using a Node.js web framework such as Express. Mapnik excels at drawing beautiful maps. However, concurrency and thread-safety are not its principal design objectives.
When drawing a map image inside a route handler, we have to ensure that map area selection (zoomToBox()) and rendering (map.render(im)) is called on a map object which is exclusive to the handler thread.
We can use a resource pool to allocated multiple map objects to be used in parallel.
We tell the pool how to create and destroy map objects.
The thread to execute the route handler will block until a map object is ready for use. If the maximum pool size is reached and all map objects in the pool are in use, the acquire() function will block until a map object becomes available.
Map Image Size
The example code assumes that the size and styling of the image is pre-defined and fixed for every call to the map service. This is the common case for tile map services such as WMTS.
For map services which can deliver variable map sizes (e.g. WMS), the map object has to be allocated inside the route handler. This usually is no problem since such services also have variable styling: Thus, the styles have to be created for every call to the service.
const mapnik = require("mapnik");
const express = require("express");
const genericPool = require("generic-pool");
// create the express app
const app = express()
// load system fonts (font directory can be configured)
mapnik.register_default_fonts();
// load plugins for data sources
mapnik.register_default_input_plugins();
// the height and width of the rendered map image
const mapImageHeight = 512;
const mapImageWidth = 512;
// create a pool for the map client to enable concurrency
const mapPool = genericPool.createPool({
// the constructor function for the pool
create: () => {
return new Promise((resolve, reject) => {
const newMap = new mapnik.Map(mapImageHeight, mapImageWidth);
// load the styles
newMap.load('./web-map-styles.xml', (err, map) => {
if (err) {
reject(new Error(err));
return;
}
// return the new map
resolve(newMap);
});
});
},
// the map destructor
destroy: (mapToBeDestroyed) => {
// return a promise
return new Promise((resolve, reject) => {
// destroy the map
delete mapToBeDestroyed;
resolve();
});
}
}, /* map pool options */ {
max: 10, // maximum size of the pool
min: 2 // minimum size of the pool
});
// create the express routes
app.get('/', async (req, res) => {
// get a map object from the pool
const map = await mapPool.acquire();
// the bounding box of the map
// fixed in this example
// But should be computed from path and/or query params
const mapBoundingBox = [6125445,2869000,6170769,2914324];
// move the map renderer to the bounding box
map.zoomToBox(mapBoundingBox);
const im = new mapnik.Image(mapImageWidth, mapImageHeight);
map.render(im, function(err, im) {
// check if any error
if (err) {
res.status(500).send(err);
mapPool.release(map);
return;
}
// create a PNG
im.encode("png", function(err, buffer) {
// check if any error
if (err) {
res.status(500).send(err);
mapPool.release(map);
return;
}
// return the png image
res.setHeader('content-type', 'image/png');
res.send(buffer);
// release the map renderer back into the pool
mapPool.release(map);
});
});
});
// start th server
app.listen(3000, () => {
console.info("map web service started!");
});
Styling your Map
Mapnik's XML Configuration File defines the layers of your map. A layer is a combination of a data source and a style: A layer tells mapnik how to fetch the data - for instance a file path - and how this data appears on the map.
Map Style Files
Often, map designers do not edit the XML Configuration File directly. Editing XML is clumsy, unaccustomed and error-prone (if you are a graphics designer 😉). Therefore, map designers invented new formats which generate the XML Configuration.
One example is CartoCSS: A map design language based on CSS syntax. Another example is
The Anatomy of the XML Configuration File
<Map background-color="#FFF" srs="+init=epsg:4326" maximum-extent="55.200,25.134,55.236,25.168">
<!-- define the re-usable style -->
<Style name="polygon-style">
<Rule>
<!-- fill color for the polygons -->
<PolygonSymbolizer fill="#a53da0"/>
</Rule>
</Style>
<Layer name="simple-polygons" srs="+init=epsg:4326">
<!-- reference to the style name -->
<StyleName>polygon-style</StyleName>
<Datasource>
<!-- The layer's data source is a ShapeFile -->
<Parameter name="type">shape</Parameter>
<!-- The file path of the ShapeFile -->
<Parameter name="file">./simple-polygons/simple-polygons.shp</Parameter>
</Datasource>
</Layer>
</Map>
The base of the xml configuration file is the <Map> element. The generic background color of the map and its maximum extent are configured through attributes. The srs defines the Spatial Reference Systems of the resulting map. The syntax of the srs is derived from the PROJ library for geodetic transformations.
The <Layer> element defines a single layer. It also declares the source data's location and projection. Mapnik accepts all common vector and raster data formats.
It is also possible to connect to a PostGIS spatial database. This is the standard way of rendering OpenStreetMap data after importing them using the osm2pgsql tool
<Map background-color="#bac2dd" srs="+init=epsg:3857" maximum-extent="6125445,2869000,6170769,2914324">
<Style name="metro-style">
<Rule>
<LineSymbolizer stroke="#FF0000" stroke-width="1.5"/>
</Rule>
</Style>
<Layer name="metro" srs="+init=epsg:3857">
<StyleName>metro-style</StyleName>
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="host">localhost</Parameter>
<Parameter name="dbname">osm</Parameter>
<Parameter name="user">quilliance</Parameter>
<Parameter name="password">fake-password</Parameter>
<Parameter name="table">dubai_metro</Parameter>
</Datasource>
</Layer>
</Map>
The table parameter can also be replaced by a subquery. This allows for dynamic selection of data to generate different layers from your database.
<Map background-color="#bac2dd" srs="+init=epsg:3857"
maximum-extent="6125445,2869000,6170769,2914324">
<Style name="metro-green-style">
<Rule>
<LineSymbolizer stroke="#00FF00" stroke-width="1.5"/>
</Rule>
</Style>
<Style name="metro-red-style">
<Rule>
<LineSymbolizer stroke="#FF0000" stroke-width="1.5"/>
</Rule>
</Style>
<!-- Dubai metro -->
<!-- the green line -->
<Layer name="metro_green_line" srs="+init=epsg:3857">
<StyleName>metro-green-style</StyleName>
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="host">localhost</Parameter>
<Parameter name="dbname">osm</Parameter>
<Parameter name="user">quilliance</Parameter>
<Parameter name="password">fake-password</Parameter>
<Parameter name="table">(SELECT geom FROM dubai_metro WHERE name = 'Green Line Metro') AS green</Parameter>
</Datasource>
</Layer>
<!-- the red line -->
<Layer name="metro_red_line" srs="+init=epsg:3857">
<StyleName>metro-red-style</StyleName>
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="host">localhost</Parameter>
<Parameter name="dbname">osm</Parameter>
<Parameter name="user">quilliance</Parameter>
<Parameter name="password">fake-password</Parameter>
<Parameter name="table">(SELECT geom FROM dubai_metro WHERE name = 'Red Line Metro') AS red</Parameter>
</Datasource>
</Layer>
</Map>
Combining Multiple Styles for a Single Layer
Your <Style> element can overload multiple styles. This way you can create complex styles for your spatial data.
The code below defines multiple symbolizers on a LineString to create a complex style. A wide red line symbolizer is below a narrower white line symbolizer to mimic a stroked polygon. A dashed gray symbolizer creates a center line.
<Style name="line-string-style">
<Rule>
<!-- the bottom red layer to mimic red border -->
<LineSymbolizer stroke="#FF0000" stroke-width="20"/>
<!-- fill with a narrower white line -->
<LineSymbolizer stroke="#FFFFFF" stroke-width="18"/>
<!-- created a dashed center line -->
<LineSymbolizer stroke="#DDDDDD" stroke-width="2" stroke-dasharray="20,20"/>
</Rule>
</Style>
Selection Rules for Styles
So far we have not examined the <Rule> element of the mapnik XML structure. It enables you to apply styling rules conditionally by using <Filter> elements. The <Filter> elements can be based on the metadata fields of your data sources.
For example, we have a database table of building sites. Each site has a polygon geometry for its area location, as well as a name attribute. Each site also has a flag to specify if it is under construction.
The building sites differ in their size. The objective is to create different map visualizations based on their polygon area size and construction state.
SELECT
name,
under_construction,
ST_GeometryType(geom) AS "Geometry",
ST_Area(ST_Transform(geom, 3857)) AS "Area"
FROM building_sites
+-------+------------------+----------+------------------+
|name |under_construction|Geometry |Area |
+-------+------------------+----------+------------------+
|A |false |ST_Polygon|2794.3865741642185|
|B |false |ST_Polygon|1443.3128581851022|
|C |false |ST_Polygon|2334.6928425244096|
|D |false |ST_Polygon|2897.8022022288023|
|E |true |ST_Polygon|1580.2358564543697|
|F |false |ST_Polygon|1944.2447310677594|
|Mall |false |ST_Polygon|15947.89585085183 |
|Small A|false |ST_Polygon|9.14439769696233 |
|Small B|false |ST_Polygon|9.475716455615675 |
|Small C|false |ST_Polygon|11.331101499298217|
+-------+------------------+----------+------------------+
The building sites differ in their size. The objective is to create different map visualizations based on their polygon area size and construction state.
<Map background-color="#FFFFFF" srs="+init=epsg:3857"
maximum-extent="6156970.262932514,2906969.4273348222,6159578.616210071,2909708.5071508246">
<Style name="building-sites-style">
<!-- regular size buildings -->
<Rule>
<Filter>[under_construction] = false and [area] > 50 and [area] < 10000</Filter>
<PolygonSymbolizer fill="#4e278e"/>
<!-- add the name as a label -->
<TextSymbolizer
face-name="DejaVu Sans Book" size="50" fill="#FFF"
placement="polygon" allow-overlap="false">
[name]
</TextSymbolizer>
</Rule>
<!-- large buildings -->
<Rule>
<Filter>[under_construction] = false and [area] > 10000</Filter>
<!-- a striped fill patter -->
<PolygonPatternSymbolizer file="./horizontal-stroke-pattern.png"/>
<LineSymbolizer stroke="#370882" stroke-width="2"/>
<!-- add text with name -->
<TextSymbolizer
face-name="DejaVu Sans Book" size="100" fill="#4e278e"
placement="polygon" allow-overlap="false">
[name]
</TextSymbolizer>
</Rule>
<!-- small size building sites (no text label) -->
<Rule>
<Filter>[under_construction] = false and [area] < 50</Filter>
<PolygonSymbolizer fill="#4e278e"/>
</Rule>
<!-- buildings under construction -->
<Rule>
<Filter>[under_construction] = true</Filter>
<PolygonSymbolizer fill="#8f77b5"/>
<LineSymbolizer stroke="#370882" stroke-width="4" stroke-dasharray="10,10"/>
<TextSymbolizer
face-name="DejaVu Sans Book" size="50" fill="#FFF"
placement="polygon" allow-overlap="false">
[name]
</TextSymbolizer>
</Rule>
</Style>
<!-- The layer for database buildings table -->
<Layer name="building-sites" srs="+init=epsg:4326">
<StyleName>building-sites-style</StyleName>
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="host">localhost</Parameter>
<Parameter name="dbname">osm</Parameter>
<Parameter name="user">quilliance</Parameter>
<Parameter name="password">fake-password</Parameter>
<!-- a query which generates the ara of the building site -->
<Parameter name="table">
(SELECT geom, name, under_construction, ST_Area(ST_Transform(geom, 3857))
AS "area" FROM building_sites) AS buildings
</Parameter>
</Datasource>
</Layer>
</Map>
The above mapnik XML configuration file produces a map image in which buildings sites are visualized by different styles based on their construction state and area size.
The database query for the <Layer> creates the area attribute.
<Parameter name="table">
(SELECT geom, name, under_construction, ST_Area(ST_Transform(geom, 3857))
AS "area" FROM building_sites) AS buildings
</Parameter>
The <Filter> elements enables us to create dynamic conditions for the <Style> definitions. Attribute fields from the query or data source are referenced by their name in brackest - for instance [area].
<Filter>[under_construction] = false and [area] > 50 and [area] < 10000</Filter>
Escaping < and >
Since this is an XML file, we need to escape the < and
> comparison operators in our
<Filter> element.
They are escaped by < and >.