Node Mapnik

mapnik .compositeOp .imageScaling .imageType .polygonFillType .threadingMode Map #add_layer #clear #clone #font #fontDirectory #fontFiles #fromString #fromStringSync #get_layer #layers #load #loadFonts #loadSync #queryMapPoint #queryPoint #render #resize #save #scale #scaleDenominator #toXML VectorTile #addData #addDataSync #addGeoJSON #addImage #addImageBuffer #addImageBufferSync #addImageSync #bufferedExtent #clear #clearSync #composite #compositeSync #empty #emptyLayers #extent #getData #getDataSync #info #layer #names #painted #paintedLayers #query #queryMany #render #reportGeometrySimplicity #reportGeometrySimplicitySync #reportGeometryValidity #reportGeometryValiditySync #setData #setDataSync #toGeoJSON #toGeoJSONSync #toJSON Image .fromBufferSync .fromBytes .fromSVG .fromSVGBytes .fromSVGBytesSync .fromSVGSync .open #clear #clearSync #compare #composite #copy #copySync #data #demultiply #demultiplySync #encode #encodeSync #fill #fillSync #filter #filterSync #fromBytesSync #getPixel #getType #height #isSolid #isSolidSync #openSync #painted #premultiplied #premultiply #premultiplySync #resize #resizeSync #save #saveSync #setGrayScaleToAlpha #setPixel #view #width Grid #addField #addField #encodeSync #height #view #width Feature .fromJSON #attributes #extent #geometry #id #toJSON blend Color #get_premultiplied #hex #set_premultiplied #toString Datasource #describe #extent #featureset #fields Geometry #extent #toJSON #toJSONSync #toWKB #toWKT #type #typeName Featureset #next Projection #forward #inverse Logger .get_severity .set_severity mapnik.ImageView
/src/node_mapnik.cpp

mapnik

Mapnik is the core of cartographic design and processing. node-mapnik provides a set of bindings to mapnik for node.js.

Plugins

Node Mapnik relies on a set of datasource input plugins that must be configured prior to using the API. These plugins are either built into Mapnik, such as the "geojson" plugin or rely on exeternal dependencies, such as GDAL. All plugin methods exist on the mapnik class level.

Plugins are referenced based on the location of the bindings on your system. These paths are generated in the lib/binding/{build}/mapnik_settings.js file. These settings can be referenced by the mapnik.settings object. We recommend using the require('path') object when building these paths:

path.resolve(mapnik.settings.paths.input_plugins, 'geojson.input')

Properties

prop type = default description
version string

current version of mapnik

module_path string

path to native mapnik binding

supports Object

indicates which of the following are supported: grid, svg, cairo, cairo_pdf, cairo_svg, png, jpeg, tiff, webp, proj4, threadsafe

versions Object

diagnostic object with versions of node, v8, boost, boost_number, mapnik, mapnik_number, mapnik_git_describe, cairo

settings Object

object that defines local paths for particular plugins and addons.

// mapnik.settings on OSX
{ 
  paths: { 
    fonts: '/Users/username/mapnik/node_modules/mapnik/lib/binding/node-v46-darwin-x64/mapnik/fonts',
    input_plugins: '/Users/username/mapnik/node_modules/mapnik/lib/binding/node-v46-darwin-x64/mapnik/input' 
  },
  env: { 
    ICU_DATA: '/Users/username/mapnik/node_modules/mapnik/lib/binding/node-v46-darwin-x64/share/mapnik/icu',
    GDAL_DATA: '/Users/username/mapnik/node_modules/mapnik/lib/binding/node-v46-darwin-x64/share/mapnik/gdal',
    PROJ_LIB: '/Users/username/mapnik/node_modules/mapnik/lib/binding/node-v46-darwin-x64/share/mapnik/proj' 
  }
}

Example

var mapnik = require('mapnik');

Static members

.compositeOp
/src/node_mapnik.cpp

compositeOp

Image type constants representing color and grayscale encodings. Composite operation constants

Properties

prop type = default description
clear number
src number
dst number
src_over number
dst_over number
src_in number
dst_in number
src_out number
dst_out number
src_atop number
dst_atop number
xor number
plus number
minus number
multiply number
screen number
overlay number
darken number
lighten number
color_dodge number
color_burn number
hard_light number
soft_light number
difference number
exclusion number
contrast number
invert number
invert-rgb number
grain_merge number
grain_extract number
hue number
saturation number
color number
linear_dodge number
linear_burn number
divide number
.imageScaling
/src/node_mapnik.cpp

imageScaling

Image scaling type constants representing color and grayscale encodings.

Properties

prop type = default description
near number
bilinear number
bicubic number
spline16 number
spline36 number
hanning number
hamming number
hermite number
kaiser number
quadric number
catrom number
gaussian number
bessel number
mitchell number
sinc number
lanczos number
blackman number
.imageType
/src/node_mapnik.cpp

imageType

Image type constants representing color and grayscale encodings.

Properties

prop type = default description
rgba8 number
gray8 number
gray8s number
gray16 number
gray16s number
gray32 number
gray32s number
gray32f number
gray64 number
gray64s number
gray64f number
.polygonFillType
/src/node_mapnik.cpp

polygonFillType

Constants representing fill types understood by Clipper during vector tile encoding.

Properties

prop type = default description
evenOdd number
nonZero number
positive number
negative number
.threadingMode
/src/node_mapnik.cpp

threadingMode

Constants representing std::async threading mode (aka launch policy).

Properties

prop type = default description
async number
deferred number
/src/mapnik_map.cpp

Map(width, height, [projection])

mapnik.Map

A map in mapnik is an object that combines data sources and styles in a way that lets you produce styled cartographic output.

Parameters

param type = default description
width int

in pixels

height int

in pixels

projection string = ('+proj)

projection as a proj4 code typically used with '+init=epsg:3857'

Properties

prop type = default description
src string
width number
height number
bufferSize number
extent Array .< number >

extent of the map as an array [ minx, miny, maxx, maxy ]

bufferedExtent Array .< number >

extent of the map's buffer [ minx, miny, maxx, maxy ]

maximumExtent Array .< number >

combination of extent and bufferedExtent [ minx, miny, maxx, maxy ]

background mapnik.Color

background color as a mapnik.Color object

Example

var map = new mapnik.Map(25, 25, '+init=epsg:3857');
console.log(map);
// {
//   aspect_fix_mode: 0,
//   parameters: {},
//   background: undefined,
//   maximumExtent: undefined,
//   bufferedExtent: [ NaN, NaN, NaN, NaN ],
//   extent:
//   [ 1.7976931348623157e+308,
//    1.7976931348623157e+308,
//    -1.7976931348623157e+308,
//    -1.7976931348623157e+308 ],
//   bufferSize: 0,
//   height: 400,
//   width: 600,
//   srs: '+init=epsg:3857'
// }

Instance members

#add_layer(new)
/src/mapnik_map.cpp

add_layer(new)

Add a new layer to this map

Parameters

param type = default description
new mapnik.Layer

layer

#clear
/src/mapnik_map.cpp

clear

Remove all layers and styles from this map

#clone
/src/mapnik_map.cpp

clone

Clone this map object, returning a value which can be changed without mutating the original

Returns

mapnik.Map :

clone

#font
/src/mapnik_map.cpp

font

Get all of the fonts currently registered as part of this map

Returns

Array .< string > :

fonts

#fontDirectory
/src/mapnik_map.cpp

fontDirectory

Get the currently-registered font directory, if any

Returns

( string | undefined ) :

fonts

#fontFiles
/src/mapnik_map.cpp

fontFiles

Get all of the fonts currently registered as part of this map, as a mapping from font to font file

Returns

Object :

fonts

#fromString(stylesheet, [options], callback)
/src/mapnik_map.cpp

fromString(stylesheet, [options], callback)

Load styles, layers, and other information for this map from a Mapnik XML stylesheet given as a string.

Parameters

param type = default description
stylesheet string

contents

options Object = ({})
callback Function

Example

var fs = require('fs');
map.fromString(fs.readFileSync('./style.xml', 'utf8'), function(err, res) {
  // details loaded
});
#fromStringSync(stylesheet, [options])
/src/mapnik_map.cpp

fromStringSync(stylesheet, [options])

Load styles, layers, and other information for this map from a Mapnik XML stylesheet given as a string.

Parameters

param type = default description
stylesheet string

contents

options Object = ({})

Example

var fs = require('fs');
map.fromStringSync(fs.readFileSync('./style.xml', 'utf8'));
#get_layer(layer)
/src/mapnik_map.cpp

get_layer(layer)

Get a layer out of this map, given a name or index

Parameters

param type = default description
layer ( string | number )

name or index

Returns

mapnik.Layer :

the layer

Throws

  • Error :

    if index is incorrect or layer is not found

#layers
/src/mapnik_map.cpp

layers

Get all of the currently-added layers in this map

Returns

Array .< mapnik.Layer > :

layers

#load(stylesheet, [options], callback)
/src/mapnik_map.cpp

load(stylesheet, [options], callback)

Load styles, layers, and other information for this map from a Mapnik XML stylesheet.

Parameters

param type = default description
stylesheet string

path

options Object = ({})
callback Function
#loadFonts
/src/mapnik_map.cpp

loadFonts

Load fonts from local or external source

#loadSync(stylesheet, [options])
/src/mapnik_map.cpp

loadSync(stylesheet, [options])

Load styles, layers, and other information for this map from a Mapnik XML stylesheet.

Parameters

param type = default description
stylesheet string

path

options Object = ({})

Example

map.loadSync('./style.xml');
#queryMapPoint(x, y, [options], callback)
/src/mapnik_map.cpp

queryMapPoint(x, y, [options], callback)

Query a Mapnik#Map object to retrieve layer and feature data based on an X and Y Mapnik#Map coordinates (use Map#queryPoint to query with geographic coordinates).

Parameters

param type = default description
x number

x coordinate

y number

y coordinate

options Object =
options.layer ( String | number ) =

layer name (string) or index (positive integer, 0 index) to query. If left blank, will query all layers.

callback Function

Returns

Array :

array - An array of Featureset objects and layer names, which each contain their own Feature objects.

Example

// iterate over the first layer returned and get all attribute information for each feature
map.queryMapPoint(10, 10, {layer: 0}, function(err, results) {
  if (err) throw err;
  console.log(results); // => [{"layer":"layer_name","featureset":{}}]
  var featureset = results[0].featureset;
  var attributes = [];
  var feature;
  while ((feature = featureset.next())) {
    attributes.push(feature.attributes());
  }
  console.log(attributes); // => [{"attr_key": "attr_value"}, {...}, {...}]
});
#queryPoint(x, y, [options], callback)
/src/mapnik_map.cpp

queryPoint(x, y, [options], callback)

Query a Mapnik#Map object to retrieve layer and feature data based on geographic coordinates of the source data (use Map#queryMapPoint to query with XY coordinates).

Parameters

param type = default description
x number

x geographic coordinate (CRS based on source data)

y number

y geographic coordinate (CRS based on source data)

options Object =
options.layer ( String | number ) =

layer name (string) or index (positive integer, 0 index) to query. If left blank, will query all layers.

callback Function

Returns

Array :

array - An array of Featureset objects and layer names, which each contain their own Feature objects.

Example

// query based on web mercator coordinates
map.queryMapPoint(-12957605.0331, 5518141.9452, {layer: 0}, function(err, results) {
  if (err) throw err;
  console.log(results); // => [{"layer":"layer_name","featureset":{}}]
  var featureset = results[0].featureset;
  var attributes = [];
  var feature;
  while ((feature = featureset.next())) {
    attributes.push(feature.attributes());
  }
  console.log(attributes); // => [{"attr_key": "attr_value"}, {...}, {...}]
});
#render(renderable, [options])
/src/mapnik_map.cpp

render(renderable, [options])

Renders a mapnik object (image tile, grid, vector tile) by passing in a renderable mapnik object.

Parameters

param type = default description
renderable mapnik.Image

mapnik object

options Object = ({})
options.buffer_size Number = (0)

size of the buffer on the image

options.scale Number = (1.0)

scale the image

options.scale_denominator Number = (0.0)
options.offset_x Number = (0)

pixel offset along the x-axis

options.offset_y Number = (0)

pixel offset along the y-axis

options.image_scaling String =

must be a valid scaling method (used when rendering a vector tile)

options.image_format String =

must be a string and valid image format (used when rendering a vector tile)

options.area_threshold Number =

used to discard small polygons by setting a minimum size (used when rendering a vector tile)

options.strictly_simple Boolean =

ensure all geometry is valid according to OGC Simple definition (used when rendering a vector tile)

options.multi_polygon_union Boolean =

union all multipolygons (used when rendering a vector tile)

options.fill_type String =

the fill type used in determining what are holes and what are outer rings. See the Clipper documentation to learn more about fill types. (used when rendering a vector tile)

options.threading_mode String =

(used when rendering a vector tile)

options.simplify_distance Number =

Simplification works to generalize geometries before encoding into vector tiles.simplification distance The simplify_distance value works in integer space over a 4096 pixel grid and uses the Douglas-Peucker algorithm. (used when rendering a vector tile)

options.variables Object =

Mapnik 3.x ONLY: A javascript object containing key value pairs that should be passed into Mapnik as variables for rendering and for datasource queries. For example if you passed vtile.render(map,image,{ variables : {zoom:1} },cb) then the @zoom variable would be usable in Mapnik symbolizers like line-width:"@zoom" and as a token in Mapnik postgis sql sub-selects like (select * from table where some_field > @zoom) as tmp (used when rendering a vector tile)

options.process_all_rings Boolean =

if true, don't assume winding order and ring order of polygons are correct according to the 2.0 Mapbox Vector Tile specification (used when rendering a vector tile)

Returns

mapnik.Map :

rendered image tile

Example

// render data to an image object
var map = new mapnik.Map(256, 256);
map.loadSync('./path/to/stylesheet.xml');
var image = new mapnik.Image(map.width, map.height);
map.render(image, {}, function(err, image) {
    if (err) throw err;
    console.log(image) // => mapnik image object with data from xml
});
// render data to a vector tile object
var map = new mapnik.Map(256, 256);
map.loadSync('./path/to/stylesheet.xml');
var vtile = new mapnik.VectorTile(9,112,195);
map.render(vtile, {}, function(err, vtile) {
    if (err) throw err;
    console.log(vtile); // => vector tile object with data from xml 
});
#resize(width, height)
/src/mapnik_map.cpp

resize(width, height)

Give this map new dimensions

Parameters

param type = default description
width number
height number
#save(file)
/src/mapnik_map.cpp

save(file)

Writes the map to an xml file

Parameters

param type = default description
file string

path

Example

map.save("path/to/map.xml");
#scale
/src/mapnik_map.cpp

scale

Get the map's scale factor. This is the ratio between pixels and geographical units like meters.

Returns

number :

scale

#scaleDenominator
/src/mapnik_map.cpp

scaleDenominator

Get the map's scale denominator.

Returns

number :

scale denominator

#toXML
/src/mapnik_map.cpp

toXML

Converts the map to an XML string

Example

var xml = map.toXML();
/src/mapnik_vector_tile.cpp

VectorTile(z, x, y)

mapnik.VectorTile

A tile generator built according to the Mapbox Vector Tile specification for compressed and simplified tiled vector data. Learn more about vector tiles here.

Parameters

param type = default description
z number

an integer zoom level

x number

an integer x coordinate

y number

an integer y coordinate

Properties

prop type = default description
x number

horizontal axis position

y number

vertical axis position

z number

the zoom level

tileSize number

the size of the tile

bufferSize number

the size of the tile's buffer

Example

var vt = new mapnik.VectorTile(9,112,195);
console.log(vt.x, vt.y, vt.z); // 9, 112, 195
console.log(vt.tileSize, vt.bufferSize); // 4096, 128

Instance members

#addData(buffer, [options], callback)
/src/mapnik_vector_tile.cpp

addData(buffer, [options], callback)

Add new vector tile data to an existing vector tile

Parameters

param type = default description
buffer Buffer

raw vector data

options object =
options.validate boolean = (false)

If true does validity checks mvt schema (not geometries) Will throw if anything invalid or unexpected is encountered in the data

options.upgrade boolean = (false)

If true will upgrade v1 tiles to adhere to the v2 specification

callback Object

Example

var data_buffer = fs.readFileSync('./path/to/data.mvt'); // returns a buffer
var vt = new mapnik.VectorTile(9,112,195);
vt.addData(data_buffer, function(err) {
  if (err) throw err;
  // your custom code
});
#addDataSync(buffer, [options])
/src/mapnik_vector_tile.cpp

addDataSync(buffer, [options])

Add raw data to this tile as a Buffer

Parameters

param type = default description
buffer Buffer

raw data

options object =
options.validate boolean = (false)

If true does validity checks mvt schema (not geometries) Will throw if anything invalid or unexpected is encountered in the data

options.upgrade boolean = (false)

If true will upgrade v1 tiles to adhere to the v2 specification

Example

var data_buffer = fs.readFileSync('./path/to/data.mvt'); // returns a buffer
// assumes you have created a vector tile object already
vt.addDataSync(data_buffer);
// your custom code
#addGeoJSON(geojson, name, [options])
/src/mapnik_vector_tile.cpp

addGeoJSON(geojson, name, [options])

Add features to this tile from a GeoJSON string. GeoJSON coordinates must be in the WGS84 longitude & latitude CRS as specified in the GeoJSON Specification.

Parameters

param type = default description
geojson string

as a string

name string

of the layer to be added

options Object =
options.area_threshold number = (0.1)

used to discard small polygons. If a value is greater than 0 it will trigger polygons with an area smaller than the value to be discarded. Measured in grid integers, not spherical mercator coordinates.

options.simplify_distance number = (0.0)

Simplification works to generalize geometries before encoding into vector tiles.simplification distance The simplify_distance value works in integer space over a 4096 pixel grid and uses the Douglas-Peucker algorithm.

options.strictly_simple boolean = (true)

ensure all geometry is valid according to OGC Simple definition

options.multi_polygon_union boolean = (false)

union all multipolygons

options.fill_type Object .< mapnik.polygonFillType > = (mapnik.polygonFillType.positive)

the fill type used in determining what are holes and what are outer rings. See the Clipper documentation to learn more about fill types.

options.process_all_rings boolean = (false)

if true, don't assume winding order and ring order of polygons are correct according to the 2.0 Mapbox Vector Tile specification

Example

var geojson = { ... };
var vt = mapnik.VectorTile(0,0,0);
vt.addGeoJSON(JSON.stringify(geojson), 'layer-name', {});
#addImage(image, name, [options])
/src/mapnik_vector_tile.cpp

addImage(image, name, [options])

Add a <mapnik.Image> as a tile layer (asynchronous)

Parameters

param type = default description
image mapnik.Image
name string

of the layer to be added

options Object =
options.image_scaling string = (bilinear)

can be any of the <mapnik.imageScaling> methods

options.image_format string = (webp)

other options include jpeg, png, tiff

Example

var vt = new mapnik.VectorTile(1, 0, 0, {
  tile_size:256
});
var im = new mapnik.Image(256, 256);
vt.addImage(im, 'layer-name', {
  image_format: 'jpeg',
  image_scaling: 'gaussian'
}, function(err) {
  if (err) throw err;
  // your custom code using `vt`  
});
#addImageBuffer(buffer, name, callback)
/src/mapnik_vector_tile.cpp

addImageBuffer(buffer, name, callback)

Add an encoded image buffer as a layer

Parameters

param type = default description
buffer Buffer

raw image data

name string

name of the layer to be added

callback Function

Example

var vt = new mapnik.VectorTile(1, 0, 0, {
  tile_size: 256
});
var image_buffer = fs.readFileSync('./path/to/image.jpg'); // returns a buffer
vt.addImageBufferSync(image_buffer, 'layer-name', function(err) {
  if (err) throw err;
  // your custom code
});
#addImageBufferSync(buffer, name)
/src/mapnik_vector_tile.cpp

addImageBufferSync(buffer, name)

Add raw image buffer as a new tile layer (synchronous)

Parameters

param type = default description
buffer Buffer

raw data

name string

name of the layer to be added

Example

var vt = new mapnik.VectorTile(1, 0, 0, {
  tile_size: 256
});
var image_buffer = fs.readFileSync('./path/to/image.jpg');
vt.addImageBufferSync(image_buffer, 'layer-name');
#addImageSync(image, name, options)
/src/mapnik_vector_tile.cpp

addImageSync(image, name, options)

Add a Image as a tile layer (synchronous)

Parameters

param type = default description
image mapnik.Image
name string

of the layer to be added

options Object
options.image_scaling string = (bilinear)

can be any of the <mapnik.imageScaling> methods

options.image_format string = (webp)

or jpeg, png, tiff

Example

var vt = new mapnik.VectorTile(1, 0, 0, {
  tile_size:256
});
var im = new mapnik.Image(256, 256);
vt.addImageSync(im, 'layer-name', {
  image_format: 'jpeg',
  image_scaling: 'gaussian'
});
#bufferedExtent
/src/mapnik_vector_tile.cpp

bufferedExtent

Get the extent including the buffer of this vector tile

Returns

Array .< number > :

extent - [minx, miny, maxx, maxy]

Example

var vt = new mapnik.VectorTile(9,112,195);
var extent = vt.bufferedExtent();
console.log(extent); // [-11273544.4277, 4693845.0329, -11190380.9409, 4777008.5197];
#clear(callback)
/src/mapnik_vector_tile.cpp

clear(callback)

Remove all data from this vector tile

Parameters

param type = default description
callback Function

Example

vt.clear(function(err) {
  if (err) throw err;
  console.log(vt.getData().length); // 0   
});
#clearSync
/src/mapnik_vector_tile.cpp

clearSync

Remove all data from this vector tile (synchronously)

Example

vt.clearSync();
console.log(vt.getData().length); // 0
#composite(array, [options], callback)
/src/mapnik_vector_tile.cpp

composite(array, [options], callback)

Composite an array of vector tiles into one vector tile

Parameters

param type = default description
array Array .< mapnik.VectorTile >

an array of vector tile objects

options object =
options.scale_factor float = (1.0)
options.offset_x number = (0)
options.offset_y number = (0)
options.area_threshold float = (0.1)

used to discard small polygons. If a value is greater than 0 it will trigger polygons with an area smaller than the value to be discarded. Measured in grid integers, not spherical mercator coordinates.

options.strictly_simple boolean = (true)

ensure all geometry is valid according to OGC Simple definition

options.multi_polygon_union boolean = (false)

union all multipolygons

options.fill_type Object .< mapnik.polygonFillType > = (mapnik.polygonFillType.positive)

the fill type used in determining what are holes and what are outer rings. See the Clipper documentation to learn more about fill types.

options.scale_denominator float = (0.0)
options.reencode boolean = (false)
options.max_extent Array .< number > = (minx,miny,maxx,maxy)
options.simplify_distance float = (0.0)

Simplification works to generalize geometries before encoding into vector tiles.simplification distance The simplify_distance value works in integer space over a 4096 pixel grid and uses the Douglas-Peucker algorithm.

options.process_all_rings boolean = (false)

if true, don't assume winding order and ring order of polygons are correct according to the 2.0 Mapbox Vector Tile specification

options.image_format string = (webp)

or jpeg, png, tiff

options.scaling_method string = (bilinear)

can be any of the <mapnik.imageScaling> methods

options.threading_mode string = (deferred)
callback Function

function(err)

Example

var vt1 = new mapnik.VectorTile(0,0,0);
var vt2 = new mapnik.VectorTile(0,0,0);
var options = {
  scale: 1.0,
  offset_x: 0,
  offset_y: 0,
  area_threshold: 0.1,
  strictly_simple: false,
  multi_polygon_union: true,
  fill_type: mapnik.polygonFillType.nonZero,
  process_all_rings:false,
  scale_denominator: 0.0,
  reencode: true
}
// add vt2 to vt1 tile
vt1.composite([vt2], options, function(err) {
  if (err) throw err;
  // your custom code with `vt1`
});
#compositeSync(array, [options])
/src/mapnik_vector_tile.cpp

compositeSync(array, [options])

Synchronous version of #VectorTile.composite

Parameters

param type = default description
array Array .< mapnik.VectorTile >

an array of vector tile objects

options object =

Example

var vt1 = new mapnik.VectorTile(0,0,0);
var vt2 = new mapnik.VectorTile(0,0,0);
var options = { ... };
vt1.compositeSync([vt2], options);
#empty
/src/mapnik_vector_tile.cpp

empty

Return whether this vector tile is empty - whether it has no layers and no features

Returns

boolean :

whether the layer is empty

Example

var vt = new mapnik.VectorTile(0,0,0);
var empty = vt.empty();
console.log(empty); // true
#emptyLayers
/src/mapnik_vector_tile.cpp

emptyLayers

Get the names of all of the empty layers in this vector tile

Returns

Array .< string > :

layer names

Example

var vt = new mapnik.VectorTile(0,0,0);
var empty = vt.emptyLayers();
// assumes you have added data to your tile
console.log(empty); // ['layer-name', 'empty-layer']
#extent
/src/mapnik_vector_tile.cpp

extent

Get the extent of this vector tile

Returns

Array .< number > :

array of extent in the form of [minx,miny,maxx,maxy]

Example

var vt = new mapnik.VectorTile(9,112,195);
var extent = vt.extent();
console.log(extent); // [-11271098.44281895, 4696291.017841229, -11192826.925854929, 4774562.534805248]
#getData([options], callback)
/src/mapnik_vector_tile.cpp

getData([options], callback)

Get the data in this vector tile as a buffer (asynchronous)

Parameters

param type = default description
options Object =
options.compression string = (none)

compression type can also be gzip

options.level int = (0)

a number 0 (no compression) to 9 (best compression)

options.strategy string

must be FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT

callback Function

Example

vt.getData({
  compression: 'gzip',
  level: 9,
  strategy: 'FILTERED'
}, function(err, data) {
  if (err) throw err;
  console.log(data); // buffer
});
#getDataSync([options])
/src/mapnik_vector_tile.cpp

getDataSync([options])

Get the data in this vector tile as a buffer (synchronous)

Parameters

param type = default description
options Object =
options.compression string = (none)

can also be gzip

options.level int = (0)

a number 0 (no compression) to 9 (best compression)

options.strategy string

must be FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT

Returns

Buffer :

raw data

Example

var data = vt.getData({
  compression: 'gzip',
  level: 9,
  strategy: 'FILTERED'
});
#info(buffer)
/src/mapnik_vector_tile.cpp

info(buffer)

Return an object containing information about a vector tile buffer. Useful for debugging .mvt files with errors.

Parameters

param type = default description
buffer Buffer

vector tile buffer

Returns

Object :

json object with information about the vector tile buffer

Example

var buffer = fs.readFileSync('./path/to/tile.mvt');
var info = mapnik.VectorTile.info(buffer);
console.log(info);
// { layers: 
//   [ { name: 'world',
//      features: 1,
//      point_features: 0,
//      linestring_features: 0,
//      polygon_features: 1,
//      unknown_features: 0,
//      raster_features: 0,
//      version: 2 },
//    { name: 'world2',
//      features: 1,
//      point_features: 0,
//      linestring_features: 0,
//      polygon_features: 1,
//      unknown_features: 0,
//      raster_features: 0,
//      version: 2 } ],
//    errors: false }
#layer(layer_name)
/src/mapnik_vector_tile.cpp

layer(layer_name)

Extract the layer by a given name to a new vector tile

Parameters

param type = default description
layer_name string

name of layer

Returns

mapnik.VectorTile :

mapnik VectorTile object

Example

var vt = new mapnik.VectorTile(0,0,0);
var data = fs.readFileSync('./path/to/data.mvt');
vt.addDataSync(data);
console.log(vt.names()); // ['layer-name', 'another-layer']
var vt2 = vt.layer('layer-name');
console.log(vt2.names()); // ['layer-name']
#names
/src/mapnik_vector_tile.cpp

names

Get the names of all of the layers in this vector tile

Returns

Array .< string > :

layer names

Example

var vt = new mapnik.VectorTile(0,0,0);
var data = fs.readFileSync('./path/to/data.mvt');
vt.addDataSync(data);
console.log(vt.names()); // ['layer-name', 'another-layer']
#painted
/src/mapnik_vector_tile.cpp

painted

Get whether the vector tile has been painted. "Painted" is a check to see if data exists in the source dataset in a tile.

Returns

boolean :

painted

Example

var vt = new mapnik.VectorTile(0,0,0);
var painted = vt.painted();
console.log(painted); // false
#paintedLayers
/src/mapnik_vector_tile.cpp

paintedLayers

Get the names of all of the painted layers in this vector tile. "Painted" is a check to see if data exists in the source dataset in a tile.

Returns

Array .< string > :

layer names

Example

var vt = new mapnik.VectorTile(0,0,0);
var painted = vt.paintedLayers();
// assumes you have added data to your tile
console.log(painted); // ['layer-name']
#query(longitude, latitude, [options], callback)
/src/mapnik_vector_tile.cpp

query(longitude, latitude, [options], callback)

Query a vector tile by longitude and latitude and get an array of features in the vector tile that exist in relation to those coordinates.

A note on tolerance: If you provide a positive value for tolerance you are saying that you'd like features returned in the query results that might not exactly intersect with a given lon/lat. The higher the tolerance the slower the query will run because it will do more work by comparing your query lon/lat against more potential features. However, this is an important parameter because vector tile storage, by design, results in reduced precision of coordinates. The amount of precision loss depends on the zoom level of a given vector tile and how aggressively it was simplified during encoding. So if you want at least one match - say the closest single feature to your query lon/lat - is is not possible to know the smallest tolerance that will work without experimentation. In general be prepared to provide a high tolerance (1-100) for low zoom levels while you should be okay with a low tolerance (1-10) at higher zoom levels and with vector tiles that are storing less simplified geometries. The units tolerance should be expressed in depend on the coordinate system of the underlying data. In the case of vector tiles this is spherical mercator so the units are meters. For points any features will be returned that contain a point which is, by distance in meters, not greater than the tolerance value. For lines any features will be returned that have a segment which is, by distance in meters, not greater than the tolerance value. For polygons tolerance is not supported which means that your lon/lat must fall inside a feature's polygon otherwise that feature will not be matched.

Parameters

param type = default description
longitude number

longitude

latitude number

latitude

options Object =
options.tolerance number = (0)

include features a specific distance from the lon/lat query in the response

options.layer string =

layer - Pass a layer name to restrict the query results to a single layer in the vector tile. Get all possible layer names in the vector tile with VectorTile#names

callback Function

(err, features)

Returns

Array .< mapnik.Feature > :

an array of mapnik.Feature objects

Example

vt.query(139.61, 37.17, {tolerance: 0}, function(err, features) {
  if (err) throw err;
  console.log(features); // array of objects
  console.log(features.length) // 1
  console.log(features[0].id()) // 89
  console.log(features[0].geometry().type()); // 'Polygon'
  console.log(features[0].distance); // 0
  console.log(features[0].layer); // 'layer name'
});
#queryMany(array, options, [callback])
/src/mapnik_vector_tile.cpp

queryMany(array, options, [callback])

Query a vector tile by multiple sets of latitude/longitude pairs. Just like <mapnik.VectorTile.query> but with more points to search.

Parameters

param type = default description
array array .< number >

longitude and latitude array pairs [[lon1,lat1], [lon2,lat2]]

options Object
options.tolerance number = (0)

include features a specific distance from the lon/lat query in the response. Read more about tolerance at VectorTile#query .

options.layer string

layer name

options.fields Array .< string > =

array of field names

callback Function =

function(err, results)

Returns

Object :

The response has contains two main objects: hits and features. The number of hits returned will correspond to the number of lon/lats queried and will be returned in the order of the query. Each hit returns 1) a distance and a 2) feature_id. The distance is number of meters the queried lon/lat is from the object in the vector tile. The feature_id is the corresponding object in features object.

The values for the query is contained in the features object. Use attributes() to extract a value.

Example

vt.queryMany([[139.61, 37.17], [140.64, 38.1]], {tolerance: 0}, function(err, results) {
  if (err) throw err;
  console.log(results.hits); // 
  console.log(results.features); // array of feature objects
  if (features.length) {
    console.log(results.features[0].layer); // 'layer-name'
    console.log(results.features[0].distance, features[0].x_hit, features[0].y_hit); // 0, 0, 0
  }
});
#render(map, surface, [options], callback)
/src/mapnik_vector_tile.cpp

render(map, surface, [options], callback)

Render/write this vector tile to a surface/image, like a Image

Parameters

param type = default description
map mapnik.Map

mapnik map object

surface mapnik.Image

renderable surface object

options Object =
options.z number =

an integer zoom level. Must be used with x and y

options.x number =

an integer x coordinate. Must be used with y and z.

options.y number =

an integer y coordinate. Must be used with x and z

options.buffer_size number =

the size of the tile's buffer

options.scale number =

floating point scale factor size to used for rendering

options.scale_denominator number =

An floating point scale_denominator to be used by Mapnik when matching zoom filters. If provided this overrides the auto-calculated scale_denominator that is based on the map dimensions and bbox. Do not set this option unless you know what it means.

options.variables Object =

Mapnik 3.x ONLY: A javascript object containing key value pairs that should be passed into Mapnik as variables for rendering and for datasource queries. For example if you passed vtile.render(map,image,{ variables : {zoom:1} },cb) then the @zoom variable would be usable in Mapnik symbolizers like line-width:"@zoom" and as a token in Mapnik postgis sql sub-selects like (select * from table where some_field > @zoom) as tmp

options.renderer string =

must be cairo or svg

options.layer ( string | number ) =

option required for grid rendering and must be either a layer name (string) or layer index (integer)

options.fields Array .< string > =

must be an array of strings

callback Function

Example

var vt = new mapnik.VectorTile(0,0,0);
var tileSize = vt.tileSize;
var map = new mapnik.Map(tileSize, tileSize);
vt.render(map, new mapnik.Image(256,256), function(err, image) {
  if (err) throw err;   
  // save the rendered image to an existing image file somewhere
  // see mapnik.Image for available methods
  image.save('./path/to/image/file.png', 'png32');
});
#reportGeometrySimplicity(callback)
/src/mapnik_vector_tile.cpp

reportGeometrySimplicity(callback)

Count the number of geometries that are not OGC simple

Parameters

param type = default description
callback Function

Example

vectorTile.reportGeometrySimplicity(function(err, simple) {
  if (err) throw err;
  console.log(simple); // array of non-simple geometries and their layer info
  console.log(simple.length); // number
});
#reportGeometrySimplicitySync
/src/mapnik_vector_tile.cpp

reportGeometrySimplicitySync

Count the number of geometries that are not OGC simple

Returns

number :

number of features that are not simple

Example

var simple = vectorTile.reportGeometrySimplicitySync();
console.log(simple); // array of non-simple geometries and their layer info
console.log(simple.length); // number
#reportGeometryValidity([options], callback)
/src/mapnik_vector_tile.cpp

reportGeometryValidity([options], callback)

Count the number of geometries that are not OGC valid

Parameters

param type = default description
options object =
options.split_multi_features boolean = (false)

If true does validity checks on multi geometries part by part Normally the validity of multipolygons and multilinestrings is done together against all the parts of the geometries. Changing this to true checks the validity of multipolygons and multilinestrings for each part they contain, rather then as a group.

options.lat_lon boolean = (false)

If true results in EPSG:4326

options.web_merc boolean = (false)

If true results in EPSG:3857

callback Function

Example

vectorTile.reportGeometryValidity(function(err, valid) {
  console.log(valid); // array of invalid geometries and their layer info
  console.log(valid.length); // number    
});
#reportGeometryValiditySync([options])
/src/mapnik_vector_tile.cpp

reportGeometryValiditySync([options])

Count the number of geometries that are not OGC valid

Parameters

param type = default description
options object =
options.split_multi_features boolean = (false)

If true does validity checks on multi geometries part by part Normally the validity of multipolygons and multilinestrings is done together against all the parts of the geometries. Changing this to true checks the validity of multipolygons and multilinestrings for each part they contain, rather then as a group.

options.lat_lon boolean = (false)

If true results in EPSG:4326

options.web_merc boolean = (false)

If true results in EPSG:3857

Returns

number :

number of features that are not valid

Example

var valid = vectorTile.reportGeometryValiditySync();
console.log(valid); // array of invalid geometries and their layer info
console.log(valid.length); // number
#setData(buffer, [options], callback)
/src/mapnik_vector_tile.cpp

setData(buffer, [options], callback)

Replace the data in this vector tile with new raw data

Parameters

param type = default description
buffer Buffer

raw data

options object =
options.validate boolean = (false)

If true does validity checks mvt schema (not geometries) Will throw if anything invalid or unexpected is encountered in the data

options.upgrade boolean = (false)

If true will upgrade v1 tiles to adhere to the v2 specification

callback Function

Example

var data = fs.readFileSync('./path/to/data.mvt');
vectorTile.setData(data, function(err) {
  if (err) throw err;
  // your custom code
});
#setDataSync(buffer, [options])
/src/mapnik_vector_tile.cpp

setDataSync(buffer, [options])

Replace the data in this vector tile with new raw data (synchronous). This function validates geometry according to the Mapbox Vector Tile specification.

Parameters

param type = default description
buffer Buffer

raw data

options object =
options.validate boolean = (false)

If true does validity checks mvt schema (not geometries) Will throw if anything invalid or unexpected is encountered in the data

options.upgrade boolean = (false)

If true will upgrade v1 tiles to adhere to the v2 specification

Example

var data = fs.readFileSync('./path/to/data.mvt');
vectorTile.setDataSync(data);
// your custom code
#toGeoJSON([layer], callback)
/src/mapnik_vector_tile.cpp

toGeoJSON([layer], callback)

Get a GeoJSON representation of this tile

Parameters

param type = default description
layer ( string | number ) = (__all__)

Can be a zero-index integer representing a layer or the string keywords __array__ or __all__ to get all layers in the form of an array of GeoJSON FeatureCollections or in the form of a single GeoJSON FeatureCollection with all layers smooshed inside

callback Function

function(err, geojson): a stringified GeoJSON of all the features in this tile

Example

vectorTile.toGeoJSON(function(err, geojson) {
  if (err) throw err;
  console.log(geojson); // stringified GeoJSON
  console.log(JSON.parse(geojson)); // GeoJSON object
});
#toGeoJSONSync([layer])
/src/mapnik_vector_tile.cpp

toGeoJSONSync([layer])

Syncronous version of VectorTile

Parameters

param type = default description
layer ( string | number ) = (__all__)

Can be a zero-index integer representing a layer or the string keywords __array__ or __all__ to get all layers in the form of an array of GeoJSON FeatureCollections or in the form of a single GeoJSON FeatureCollection with all layers smooshed inside

Returns

string :

stringified GeoJSON of all the features in this tile.

Example

var geojson = vectorTile.toGeoJSONSync();
geojson // stringified GeoJSON
JSON.parse(geojson); // GeoJSON object
#toJSON([options])
/src/mapnik_vector_tile.cpp

toJSON([options])

Get a JSON representation of this tile

Parameters

param type = default description
options Object =
options.decode_geometry boolean = (false)

return geometry as integers relative to the tile grid

Returns

Object :

json representation of this tile with name, extent, version, and feature properties

Example

var vt = mapnik.VectorTile(10,131,242);
var buffer = fs.readFileSync('./path/to/data.mvt');
vt.setData(buffer);
var json = vectorTile.toJSON();
console.log(json); 
// { 
//   name: 'layer-name',
//   extent: 4096, 
//   version: 2,
//   features: [ ... ] // array of objects
// }
/src/mapnik_image.cpp

Image(width, height, [options])

mapnik.Image

Create a new image object (surface) that can be used for rendering data to.

Parameters

param type = default description
width number

width in pixels

height number

height in pixels

options Object =
options.type Object .< mapnik.imageType > = (mapnik.imageType.rgb8)

a mapnik.imageType object

options.initialize boolean = (true)
options.premultiplied boolean = (false)
options.painted boolean = (false)

Properties

prop type = default description
offset number

offset number

scaling number

scaling number

Throws

  • TypeError :

    if any argument is the wrong type, like if width or height is not numeric.

Example

var im = new mapnik.Image(256, 256, {
  premultiplied: true,
  type: mapnik.imageType.gray8
});

Static members

.fromBufferSync(width, height, buffer)
/src/mapnik_image.cpp

fromBufferSync(width, height, buffer)

Create an image of the existing buffer.

Note: the buffer must live as long as the image. It is recommended that you do not use this method. Be warned!

Parameters

param type = default description
width number
height number
buffer Buffer

Returns

mapnik.Image :

image object

Example

var img = new mapnik.Image.open('./path/to/image.png');
var buffer = img.data(); // returns data as buffer
var img2 = mapnik.Image.fromBufferSync(img.width(), img.height(), buffer);
.fromBytes(buffer, [options], callback)
/src/mapnik_image.cpp

fromBytes(buffer, [options], callback)

Create an image from a byte stream buffer.

Parameters

param type = default description
buffer Buffer

image buffer

options Object =
options.premultiply Boolean =

Default false, if true, then the image will be premultiplied before being returned

options.max_size Number =

the maximum allowed size of the image dimensions. The default is 2048.

callback Function

function(err, img)

Example

var buffer = fs.readFileSync('./path/to/image.png');
mapnik.Image.fromBytesSync(buffer, function(err, img) {
  if (err) throw err;
  // your custom code with `img` object
});
.fromSVG(filename, [options], callback)
/src/mapnik_image.cpp

fromSVG(filename, [options], callback)

Create a new image from an SVG file

Parameters

param type = default description
filename string
options Object =
options.scale number =

scale the image. For example passing 0.5 as scale would render your SVG at 50% the original size.

options.max_size number =

the maximum allowed size of the svg dimensions * scale. The default is 2048. This option can be passed a smaller or larger size in order to control the final size of the image allocated for rasterizing the SVG.

callback Function

Example

mapnik.Image.fromSVG('./path/to/image.svg', {scale: 0.5}, function(err, img) {
  if (err) throw err;
  // new img object (at 50% scale)
});
.fromSVGBytes(path, [options], callback)
/src/mapnik_image.cpp

fromSVGBytes(path, [options], callback)

Load image from an SVG buffer

Parameters

param type = default description
path string

path to SVG image

options Object =
options.scale number =

scale the image. For example passing 0.5 as scale would render your SVG at 50% the original size.

options.max_size number =

the maximum allowed size of the svg dimensions * scale. The default is 2048. This option can be passed a smaller or larger size in order to control the final size of the image allocated for rasterizing the SVG.

callback Function

= function(err, img)

Example

var buffer = fs.readFileSync('./path/to/image.svg');
mapnik.Image.fromSVGBytesSync(buffer, function(err, img) {
  if (err) throw err;
  // your custom code with `img`
});
.fromSVGBytesSync(path, [options])
/src/mapnik_image.cpp

fromSVGBytesSync(path, [options])

Load image from an SVG buffer (synchronous)

Parameters

param type = default description
path string

path to SVG image

options Object =
options.scale number =

scale the image. For example passing 0.5 as scale would render your SVG at 50% the original size.

options.max_size number =

the maximum allowed size of the svg dimensions * scale. The default is 2048. This option can be passed a smaller or larger size in order to control the final size of the image allocated for rasterizing the SVG.

Returns

mapnik.Image :

Image object

Example

var buffer = fs.readFileSync('./path/to/image.svg');
var img = mapnik.Image.fromSVGBytesSync(buffer);
.fromSVGSync(filename, [options])
/src/mapnik_image.cpp

fromSVGSync(filename, [options])

Create a new image from an SVG file (synchronous)

Parameters

param type = default description
filename string
options Object =
options.scale number =

scale the image. For example passing 0.5 as scale would render your SVG at 50% the original size.

options.max_size number =

the maximum allowed size of the svg dimensions * scale. The default is 2048. This option can be passed a smaller or larger size in order to control the final size of the image allocated for rasterizing the SVG.

Returns

mapnik.Image :

image object

Example

var img = mapnik.Image.fromSVG('./path/to/image.svg');
.open(path, callback)
/src/mapnik_image.cpp

open(path, callback)

Load in a pre-existing image as an image object

Parameters

param type = default description
path string

path to the image you want to load

callback Function

-

Example

mapnik.Image.open('./path/to/image.jpg', function(err, img) {
  if (err) throw err;
  // img is now an Image object
});

Instance members

#clear(callback)
/src/mapnik_image.cpp

clear(callback)

Make this image transparent, removing all image data from it.

Parameters

param type = default description
callback Function

Example

var img = new mapnik.Image(5,5);
img.fillSync(1);
console.log(img.getPixel(0, 0)); // 1
img.clear(function(err, result) {
  console.log(result.getPixel(0,0)); // 0
});
#clearSync
/src/mapnik_image.cpp

clearSync

Make this image transparent. (synchronous)

Example

var img = new mapnik.Image(5,5);
img.fillSync(1);
console.log(img.getPixel(0, 0)); // 1
img.clearSync();
console.log(img.getPixel(0, 0)); // 0
#compare(image, [options])
/src/mapnik_image.cpp

compare(image, [options])

Compare the pixels of one image to the pixels of another. Returns the number of pixels that are different. So, if the images are identical then it returns 0. And if the images share no common pixels it returns the total number of pixels in an image which is equivalent to im.width()*im.height().

Parameters

param type = default description
image mapnik.Image

another mapnik.Image instance to compare to

options Object =
options.threshold number = (16)

A value that should be 0 or greater to determine if the pixels match. Defaults to 16 which means that rgba(0,0,0,0) would be considered the same as rgba(15,15,15,0).

options.alpha boolean = (true)

alpha value, along with rgb, is considered when comparing pixels

Returns

number :

quantified visual difference between these two images in "number of pixels" (i.e. 80 pixels are different);

Example

// start with the exact same images
var img1 = new mapnik.Image(2,2);
var img2 = new mapnik.Image(2,2);
console.log(img1.compare(img2)); // 0

// change 1 pixel in img2
img2.setPixel(0,0, new mapnik.Color('green'));
console.log(img1.compare(img2)); // 1

// difference in color at first pixel
img1.setPixel(0,0, new mapnik.Color('red'));
console.log(img1.compare(img2)); // 1

// two pixels different
img2.setPixel(0,1, new mapnik.Color('red'));
console.log(img1.compare(img2)); // 2

// all pixels different
img2.setPixel(1,1, new mapnik.Color('blue'));
img2.setPixel(1,0, new mapnik.Color('blue'));
console.log(img1.compare(img2)); // 4
#composite(image, [options], callback)
/src/mapnik_image.cpp

composite(image, [options], callback)

Overlay this image with another image, creating a layered composite as a new image

Parameters

param type = default description
image mapnik.Image

image to composite with

options Object =
options.comp_op mapnik.compositeOp =

compositing operation. Must be an integer value that relates to a compositing operation.

options.opacity number =

opacity must be a floating point number between 0-1

options.dx number =
options.dy number =
options.image_filters string =

a string of filter names

callback Function

Example

var img1 = new mapnik.Image.open('./path/to/image.png');
var img2 = new mapnik.Image.open('./path/to/another-image.png');
img1.composite(img2, {
  comp_op: mapnik.compositeOp['multiply'],
  dx: 0,
  dy: 0,
  opacity: 0.5,
  image_filters: 'invert agg-stack-blur(10,10)'
}, function(err, result) {
  if (err) throw err;
  // new image with `result`
});
#copy(type, [options], callback)
/src/mapnik_image.cpp

copy(type, [options], callback)

Copy an image into a new image by creating a clone

Parameters

param type = default description
type number

image type to clone into, can be any mapnik.imageType number

options Object = ({})
options.scaling number =

scale the image

options.offset number =

offset this image

callback Function

Example

var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray16});
var img2 = img.copy(mapnik.imageType.gray8, function(err, img2) {
  if (err) throw err;
  // custom code with `img2` converted into gray8 type
});
#copySync(type, [options])
/src/mapnik_image.cpp

copySync(type, [options])

Copy an image into a new image by creating a clone

Parameters

param type = default description
type number

image type to clone into, can be any mapnik.imageType number

options Object = ({})
options.scaling number =

scale the image

options.offset number =

offset this image

Returns

mapnik.Image :

copy

Example

var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray16});
var img2 = img.copy(mapnik.imageType.gray8);
// custom code with `img2` as a gray8 type
#data
/src/mapnik_image.cpp

data

Return a copy of the pixel data in this image as a buffer

Returns

Buffer :

pixel data as a buffer

Example

var img = new mapnik.Image.open('./path/to/image.png');
var buffr = img.data();
#demultiply(callback)
/src/mapnik_image.cpp

demultiply(callback)

Demultiply the pixels in this image, asynchronously. The opposite of premultiplying

Parameters

param type = default description
callback Function
#demultiplySync
/src/mapnik_image.cpp

demultiplySync

Demultiply the pixels in this image. The opposite of premultiplying.

#encode([format], [options], callback)
/src/mapnik_image.cpp

encode([format], [options], callback)

Encode this image into a buffer of encoded data

Parameters

param type = default description
format string = (png)

image format

options Object =
options.palette mapnik.Palette =

mapnik.Palette object

callback Function

function(err, encoded)

Returns

Buffer :

encoded image data

Example

var img = new mapnik.Image.open('./path/to/image.png');
myImage.encode('png', function(err, encoded) {
  if (err) throw err;
  // write buffer to new file
  fs.writeFileSync('myimage.png', encoded);
});

// encoding an image object with a mapnik.Palette
var im = new mapnik.Image(256, 256);
var pal = new mapnik.Palette(new Buffer('\xff\x09\x93\xFF\x01\x02\x03\x04','ascii'));
im.encode('png', {palette: pal}, function(err, encode) {
  if (err) throw err;
  // your custom code with `encode` image buffer
});
#encodeSync([format], [options])
/src/mapnik_image.cpp

encodeSync([format], [options])

Encode this image into a buffer of encoded data (synchronous)

Parameters

param type = default description
format string = (png)

image format

options Object =
options.palette mapnik.Palette =

mapnik.Palette object

Returns

Buffer :

buffer - encoded image data

Example

var img = new mapnik.Image.open('./path/to/image.png');
var buffer = img.encodeSync('png');
// write buffer to a new file
fs.writeFileSync('myimage.png', buffer);
#fill(color, callback)
/src/mapnik_image.cpp

fill(color, callback)

Fill this image with a given color. Changes all pixel values.

Parameters

param type = default description
color ( mapnik.Color | number )
callback Function

function(err, img)

Example

var img = new mapnik.Image(5,5);
img.fill(new mapnik.Color('blue'), function(err, img) {
  if (err) throw err;
  var colors = img.getPixel(0,0, {get_color: true});
  pixel is colored blue
  console.log(color.b); // 255
});

// or fill with rgb string
img.fill('rgba(255,255,255,0)', function(err, img) { ... });
#fillSync(color)
/src/mapnik_image.cpp

fillSync(color)

Fill this image with a given color. Changes all pixel values. (synchronous)

Parameters

param type = default description
color ( mapnik.Color | number )

Example

var img = new mapnik.Image(5,5);
// blue pixels
img.fillSync(new mapnik.Color('blue'));
var colors = img.getPixel(0,0, {get_color: true});
// blue value is filled
console.log(colors.b); // 255
#filter(filter, callback)
/src/mapnik_image.cpp

filter(filter, callback)

Apply a filter to this image. Changes all pixel values.

Parameters

param type = default description
filter string

can be blur, emboss, sharpen, sobel, or gray.

callback Function

function(err, img)

Example

var img = new mapnik.Image(5, 5);
img.filter('sobel', function(err, img) {
  if (err) throw err;
  // your custom `img` with sobel filter
  // https://en.wikipedia.org/wiki/Sobel_operator
});
#filterSync(filter)
/src/mapnik_image.cpp

filterSync(filter)

Apply a filter to this image. This changes all pixel values. (synchronous)

Parameters

param type = default description
filter string

can be blur, emboss, sharpen, sobel, or gray.

Example

var img = new mapnik.Image(5, 5);
img.filter('blur');
// your custom code with `img` having blur applied
#fromBytesSync(buffer)
/src/mapnik_image.cpp

fromBytesSync(buffer)

Create an image from a byte stream buffer. (synchronous)

Parameters

param type = default description
buffer Buffer

image buffer

Returns

mapnik.Image :

image object

Example

var buffer = fs.readFileSync('./path/to/image.png');
var img = new mapnik.Image.fromBytesSync(buffer);
#getPixel(x, y, [options])
/src/mapnik_image.cpp

getPixel(x, y, [options])

Get a specific pixel and its value

Parameters

param type = default description
x number

position within image from top left

y number

position within image from top left

options Object =

the only valid option is get_color, which should be a boolean. If set, the return is an Object with rgba values instead of a pixel number.

Returns

( number | Object ) :

color number or object of rgba values

Example

// check for color after rendering image
var img = new mapnik.Image(4, 4);
var map = new mapnik.Map(4, 4);
map.background = new mapnik.Color('green');
map.render(img, {},function(err, img) {
  console.log(img.painted()); // false
  var pixel = img.getPixel(0,0);
  var values = img.getPixel(0,0, {get_color: true});
  console.log(pixel); // 4278222848
  console.log(values); // { premultiplied: false, a: 255, b: 0, g: 128, r: 0 }
});
#getType
/src/mapnik_image.cpp

getType

Determine the image type

Returns

number :

Number of the image type

Example

var img = new mapnik.Image(256, 256, {
  type: mapnik.imageType.gray8
});
var type = img.getType();
var typeCheck = mapnik.imageType.gray8;
console.log(type, typeCheck); // 1, 1
#height
/src/mapnik_image.cpp

height

Get this image's height in pixels

Returns

number :

height

Example

var img = new mapnik.Image(4,4);
console.log(img.height()); // 4
#isSolid
/src/mapnik_image.cpp

isSolid

Test if an image's pixels are all exactly the same

Returns

boolean :

true means all pixels are exactly the same

Example

var img = new mapnik.Image(2,2);
console.log(img.isSolid()); // true

// change a pixel
img.setPixel(0,0, new mapnik.Color('green'));
console.log(img.isSolid()); // false
#isSolidSync
/src/mapnik_image.cpp

isSolidSync

Determine whether the image is solid - whether it has alpha values of greater than one.

Returns

boolean :

whether the image is solid

Example

var img = new mapnik.Image(256, 256);
var view = img.view(0, 0, 256, 256);
console.log(view.isSolidSync()); // true
#openSync(path)
/src/mapnik_image.cpp

openSync(path)

Load in a pre-existing image as an image object

Parameters

param type = default description
path string

path to the image you want to load

Returns

mapnik.Image :

new image object based on existing image

Example

var img = new mapnik.Image.open('./path/to/image.jpg');
#painted
/src/mapnik_image.cpp

painted

Check if this image is painted. "Painted" refers to if it has data or not. An image created with new mapnik.Image(4,4) defaults to false since we loaded a new image without rendering and have no idea if it was painted or not. You can run new mapnik.Image(4, 4, {painted: true}) to manually set the painted value.

Returns

boolean :

whether it is painted or not

Example

var img = new mapnik.Image(5,5);
console.log(img.painted()); // false
#premultiplied
/src/mapnik_image.cpp

premultiplied

Determine whether the given image is premultiplied. https://en.wikipedia.org/wiki/Alpha_compositing

Returns

boolean :

premultiplied true if the image is premultiplied

Example

var img = new mapnik.Image(5,5);
console.log(img.premultiplied()); // false
img.premultiplySync()
console.log(img.premultiplied()); // true
#premultiply(callback)
/src/mapnik_image.cpp

premultiply(callback)

Premultiply the pixels in this image, asynchronously

Parameters

param type = default description
callback Function

Example

var img = new mapnik.Image(5,5);
img.premultiply(function(err, img) {
  if (err) throw err;
  // your custom code with premultiplied img
})
#premultiplySync
/src/mapnik_image.cpp

premultiplySync

Premultiply the pixels in this image.

Example

var img = new mapnik.Image(5,5);
img.premultiplySync();
console.log(img.premultiplied()); // true
#resize(width, height, [options], callback)
/src/mapnik_image.cpp

resize(width, height, [options], callback)

Resize this image (makes a copy)

Parameters

param type = default description
width number

in pixels

height number

in pixels

options Object = ({})
options.offset_x number = (0)

offset the image horizontally in pixels

options.offset_y number = (0)

offset the image vertically in pixels

options.scaling_method mapnik.imageScaling = (mapnik.imageScaling.near)

scaling method

options.filter_factor number = (1.0)
callback Function

function(err, result)

Example

var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray8});
img.resize(8, 8, function(err, result) {
  if (err) throw err;
  // new image object as `result`
});
#resizeSync(width, height, [options])
/src/mapnik_image.cpp

resizeSync(width, height, [options])

Resize this image (makes a copy). Synchronous version of mapnik.Image.resize .

Parameters

param type = default description
width number
height number
options Object = ({})
options.offset_x number = (0)

offset the image horizontally in pixels

options.offset_y number = (0)

offset the image vertically in pixels

options.scaling_method mapnik.imageScaling = (mapnik.imageScaling.near)

scaling method

options.filter_factor number = (1.0)

Returns

mapnik.Image :

copy

Example

var img = new mapnik.Image(4, 4, {type: mapnik.imageType.gray8});
var img2 = img.resizeSync(8, 8);
// new copy as `img2`
#save(filename, [format], callback)
/src/mapnik_image.cpp

save(filename, [format], callback)

Encode this image and save it to disk as a file.

Parameters

param type = default description
filename string
format string = (png)
callback Function

Example

img.save('image.png', 'png', function(err) {
  if (err) throw err;
  // your custom code
});
#saveSync(filename, [format])
/src/mapnik_image.cpp

saveSync(filename, [format])

Encode this image and save it to disk as a file.

Parameters

param type = default description
filename string
format string = (png)

Example

img.saveSync('foo.png');
#setGrayScaleToAlpha(color)
/src/mapnik_image.cpp

setGrayScaleToAlpha(color)

Convert all grayscale values to alpha values. Great for creating a mask layer based on alpha values.

Parameters

param type = default description
color mapnik.Color

Example

var image = new mapnik.Image(2,2);
image.fillSync(new mapnik.Color('rgba(0,0,0,255)'));
console.log(image.getPixel(0,0, {get_color:true})); // { premultiplied: false, a: 255, b: 0, g: 0, r: 0 }

image.setGrayScaleToAlpha();
// turns a black pixel into a completely transparent mask
console.log(image.getPixel(0,0, {get_color:true})); // { premultiplied: false, a: 0, b: 255, g: 255, r: 255 }
#setPixel(x, y, numeric)
/src/mapnik_image.cpp

setPixel(x, y, numeric)

Set a pixels value

Parameters

param type = default description
x number

position within image from top left

y number

position within image from top left

numeric ( Object | number )

or object representation of a color, typically used with mapnik.Color

Example

var gray = new mapnik.Image(256, 256);
gray.setPixel(0,0,new mapnik.Color('white'));
var pixel = gray.getPixel(0,0,{get_color:true});
console.log(pixel); // { premultiplied: false, a: 255, b: 255, g: 255, r: 255 }
#view(x, y, width, height)
/src/mapnik_image.cpp

view(x, y, width, height)

Get a constrained view of this image given x, y, width, height parameters.

Parameters

param type = default description
x number
y number
width number
height number

Returns

mapnik.Image :

an image constrained to this new view

Example

var img = new mapnik.Image(10, 10);
// This function says "starting from the 0/0 pixel, grab 5 pixels along
// the x-axis and 5 along the y-axis" which gives us a quarter of the original
// 10x10 pixel image
var img2 = img.view(0, 0, 5, 5);
console.log(img.width(), img2.width()); // 10, 5
#width
/src/mapnik_image.cpp

width

Get this image's width in pixels

Returns

number :

width

Example

var img = new mapnik.Image(4,4);
console.log(img.width()); // 4
/src/mapnik_grid.cpp

Grid(width, height, [options])

mapnik.Grid

Generator for UTFGrid representations of data.

Parameters

param type = default description
width number
height number
options Object = ({})

optional argument, which can have a 'key' property

Properties

prop type = default description
key string

Instance members

#addField
/src/mapnik_grid.cpp

addField

Get all of this grid's fields

#addField(field)
/src/mapnik_grid.cpp

addField(field)

Add a field to this grid's output

Parameters

param type = default description
field string
#encodeSync([options])
/src/mapnik_grid.cpp

encodeSync([options])

Get a constrained view of this field given x, y, width, height parameters.

Parameters

param type = default description
options Object = ({resolution:4,features:false})

Returns

Object :

an encoded field with grid, keys, and data members.

#height
/src/mapnik_grid.cpp

height

Get this grid's height

Returns

number :

height

#view(x, y, width, height)
/src/mapnik_grid.cpp

view(x, y, width, height)

Get a constrained view of this field given x, y, width, height parameters.

Parameters

param type = default description
x number
y number
width number
height number

Returns

mapnik.Grid :

a grid constrained to this new view

#width
/src/mapnik_grid.cpp

width

Get this grid's width

Returns

number :

width

/src/mapnik_feature.cpp

Feature

mapnik.Feature

A single geographic feature, with geometry and properties. This is typically derived from data by a datasource, but can be manually created.

Static members

.fromJSON(geojson)
/src/mapnik_feature.cpp

fromJSON(geojson)

Parameters

param type = default description
geojson string

string

Create a feature from a GeoJSON representation.

Instance members

#attributes
/src/mapnik_feature.cpp

attributes

Get the feature's attributes as an object.

Returns

Object :

attributes

#extent
/src/mapnik_feature.cpp

extent

Get the feature's extent

Returns

Array .< number > :

extent [minx, miny, maxx, maxy] order feature extent.

#geometry
/src/mapnik_feature.cpp

geometry

Get the feature's attributes as a Mapnik geometry.

Returns

mapnik.Geometry :

geometry

#id
/src/mapnik_feature.cpp

id

Returns

number :

id the feature's internal id

#toJSON
/src/mapnik_feature.cpp

toJSON

Generate and return a GeoJSON representation of this feature

Returns

string :

geojson Feature object in stringified GeoJSON

/src/blend.cpp

blend(buffers, options, callback)

mapnik.Blend

Composite multiple images on top of each other, with strong control over how the images are combined, resampled, and blended.

Parameters

param type = default description
buffers Array .< Buffer >

an array of buffers

options Object

can include width, height, compression, reencode, palette, mode can be either hextree or octree, quality. JPEG & WebP quality quality ranges from 0-100, PNG quality from 2-256. Compression varies by platform - it references the internal zlib compression algorithm.

callback Function

called with (err, res), where a successful result is a processed image as a Buffer

Example

mapnik.blend([
 fs.readFileSync('foo.png'),
 fs.readFileSync('bar.png'),
], function(err, result) {
 if (err) throw err;
 fs.writeFileSync('result.png', result);
});
/src/mapnik_color.cpp

Color(value, r, g, b, pre)

mapnik.Color

A mapnik.Color object used for handling and converting colors

Parameters

param type = default description
value ( string | number )

either an array of [r, g, b, a], a color keyword, or a CSS color in rgba() form.

r number

red value between 0 and 255

g number

green value between 0 and 255

b number

blue value between 0 and 255

pre boolean

premultiplied, either true or false

Throws

  • TypeError :

    if a rgb component is outside of the 0-255 range

Example

var c = new mapnik.Color('green');
var c = new mapnik.Color(0, 128, 0, 255);
// premultiplied
var c = new mapnik.Color(0, 128, 0, 255, true);

Instance members

#get_premultiplied
/src/mapnik_color.cpp

get_premultiplied

Get whether this color is premultiplied

Returns

boolean :

premultiplied

#hex
/src/mapnik_color.cpp

hex

Get this color represented as a hexademical string

Returns

string :

hex representation

Example

var c = new mapnik.Color('green');
c.hex();
// '#008000'
#set_premultiplied(premultiplied)
/src/mapnik_color.cpp

set_premultiplied(premultiplied)

Set whether this color should be premultiplied

Parameters

param type = default description
premultiplied boolean

Throws

Example

var c = new mapnik.Color('green');
c.set_premultiplied(true);
#toString
/src/mapnik_color.cpp

toString

Get this color's representation as a string

Returns

string :

color as a string

Example

var green = new mapnik.Color('green');
green.toString()
// 'rgb(0,128,0)'
/src/mapnik_datasource.cpp

Datasource

mapnik.Datasource

A Datasource object. This is the connector from Mapnik to any kind of file, network, or database source of geographical data.

Instance members

#describe
/src/mapnik_datasource.cpp

describe

Describe the datasource's contents and type.

Returns

Object :

description: an object with type, fields, encoding, geometry_type, and proj4 code

#extent
/src/mapnik_datasource.cpp

extent

Get the Datasource's extent

Returns

Array .< number > :

extent [minx, miny, maxx, maxy] order feature extent.

#featureset([options])
/src/mapnik_datasource.cpp

featureset([options])

Get features from this dataset using an iterator.

Parameters

param type = default description
options Object =
options.extent Array .< number > = ([minx,miny,maxx,maxy])

Returns

Object :

an iterator with a .next() method that returns features from a dataset.

Example

var features = [];
var featureset = ds.featureset();
var feature;
while ((feature = featureset.next())) {
    features.push(feature);
}
#fields
/src/mapnik_datasource.cpp

fields

Get only the fields metadata from a dataset.

Returns

Object :

an object that maps from a field name to it type

Example

var fields = ds.fields();
// {
//     FIPS: 'String',
//     ISO2: 'String',
//     ISO3: 'String',
//     UN: 'Number',
//     NAME: 'String',
//     AREA: 'Number',
//     POP2005: 'Number',
//     REGION: 'Number',
//     SUBREGION: 'Number',
//     LON: 'Number',
//     LAT: 'Number'
// }
/src/mapnik_geometry.cpp

Geometry

mapnik.Geometry

Geometry: a representation of geographical features in terms of shape alone. This class provides many useful functions for conversion to and from formats.

You'll never create a mapnik.Geometry instance manually: it is always part of a mapnik.Feature instance, which is often a part of a mapnik.Featureset instance.

Instance members

#extent
/src/mapnik_geometry.cpp

extent

Get the geometry's extent

Returns

Array .< number > :

extent [minx, miny, maxx, maxy] order geometry extent.

#toJSON([options], callback)
/src/mapnik_geometry.cpp

toJSON([options], callback)

Convert this geometry into a GeoJSON representation, asynchronously.

Parameters

param type = default description
options Object = ({})

. The only supported object is transform, which should be a valid mapnik.ProjTransform object.

callback Function

called with (err, result)

#toJSONSync
/src/mapnik_geometry.cpp

toJSONSync

Convert this geometry into a GeoJSON representation, synchronously.

Returns

string :

GeoJSON, string-encoded representation of this geometry.

#toWKB
/src/mapnik_geometry.cpp

toWKB

Get the geometry's representation as Well-Known Binary

Returns

string :

wkb representation of this geometry

#toWKT
/src/mapnik_geometry.cpp

toWKT

Get the geometry's representation as Well-Known Text

Returns

string :

wkt representation of this geometry

#type
/src/mapnik_geometry.cpp

type

Get the geometry type

Returns

string :

type of geometry.

#typeName
/src/mapnik_geometry.cpp

typeName

Get the geometry's representation as a GeoJSON type

Returns

string :

GeoJSON type representation of this geometry

/src/mapnik_featureset.cpp

Featureset

mapnik.Featureset

An iterator of mapnik.Feature objects.

Instance members

#next
/src/mapnik_featureset.cpp

next

Return the next Feature in this featureset if it exists, or null if it does not.

Returns

( mapnik.Feature | null ) :

next feature

/src/mapnik_projection.cpp

Projection(projection, [options])

mapnik.Projection

A geographical projection: this class makes it possible to translate between locations in different projections

Parameters

param type = default description
projection string

projection as a proj4 definition string

options Object = ({lazy:false})

whether to lazily instantiate the data backing this projection.

Throws

  • TypeError :

    if the projection string or options argument is the wrong type

  • Error :

    the projection could not be initialized - it was not found in proj4's tables or the string was malformed

Example

var wgs84 = new mapnik.Projection('+init=epsg:4326');

Instance members

#forward(position)
/src/mapnik_projection.cpp

forward(position)

Project from a position in WGS84 space to a position in this projection.

Parameters

param type = default description
position Array .< number >

as [x, y] or extent as [minx,miny,maxx,maxy]

Returns

Array .< number > :

projected coordinates

Example

var merc = new mapnik.Projection('+init=epsg:3857');
var long_lat_coords = [-122.33517, 47.63752];
var projected = merc.forward(long_lat_coords);
#inverse(position)
/src/mapnik_projection.cpp

inverse(position)

Unproject from a position in this projection to the same position in WGS84 space.

Parameters

param type = default description
position Array .< number >

as [x, y] or extent as [minx,miny,maxx,maxy]

Returns

Array .< number > :

unprojected coordinates

/src/mapnik_logger.cpp

Logger

mapnik.Logger

No constructor - Severity level is only available via mapnik.Logger static instance.

Example

mapnik.Logger.setSeverity(mapnik.Logger.NONE);
var log = mapnik.Logger.get_severity();
console.log(log); // 3

Static members

.get_severity
/src/mapnik_logger.cpp

get_severity

Returns integer which represents severity level

Returns

number :

severity level

.set_severity(severity)
/src/mapnik_logger.cpp

set_severity(severity)

Accepts level of severity as a mapnik constant

Available security levels

Parameters

param type = default description
severity number

severity level

Returns

number :

severity level

/src/mapnik_image_view.cpp

mapnik.ImageView(left, top, width, height)

This is usually not initialized directly: you'll use the mapnik.Image#view method to instantiate an instance.

Parameters

param type = default description
left number
top number
width number
height number

Throws

  • TypeError :

    if any argument is missing or not numeric

Example

var im = new mapnik.Image(256, 256);
var view = im.view(0, 0, 256, 256);