Mapnik
mapnik .compositeOp .imageScaling .imageType .polygonFillType .threadingMode mapnik.Color #get_premultiplied #hex #set_premultiplied #toString mapnik.Datasource #describe #extent mapnik.Feature .fromJSON #attributes #extent #geometry #id #toJSON mapnik.Featureset #next mapnik.Geometry #extent #toJSON #toJSONSync #toWKB #toWKT #type mapnik.Grid #addField #addField #encodeSync #height #view #width mapnik.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 mapnik.ImageView mapnik.Logger .get_severity .set_severity mapnik.Map #add_layer #clear #clone #font #fontDirectory #fontFiles #fromStringSync #fromStringSync #get_layer #layers #load #loadFonts #loadSync #resize #scale #scaleDenominator mapnik.Projection #forward #inverse mapnik.VectorTile #addData #addDataSync #addGeoJSON #addImage #addImageBuffer #addImageBufferSync #addImageSync #bufferedExtent #clear #clearSync #composite #compositeSync #empty #emptyLayers #extent #getData #getDataSync #names #painted #paintedLayers #query #queryMany #render #reportGeometrySimplicity #reportGeometrySimplicitySync #reportGeometryValidity #reportGeometryValiditySync #setData #setDataSync #toGeoJSON #toGeoJSONSync #toJSON mapnik.blend

mapnik

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

property type 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

Examples

var mapnik = require('node-mapnik');

compositeOp

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

property type 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 number

-rgb

grain_merge number
grain_extract number
hue number
saturation number
color number
linear_dodge number
linear_burn number
divide number

imageScaling

Image scaling type constants representing color and grayscale encodings.

property type 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

Image type constants representing color and grayscale encodings.

property type description
rgba8 number
gray8 number
gray8s number
gray16 number
gray16s number
gray32 number
gray32s number
gray32f number
gray64 number
gray64s number
gray64f number

polygonFillType

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

property type description
evenOdd number
nonZero number
positive number
negative number

threadingMode

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

property type description
async number
deferred number

mapnik.Color(value, green, blue, blue, premultiplied)

parameter type description
value string or number

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

green number
blue number
blue number
premultiplied boolean

Throws

exception description
TypeError

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

Examples

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);

get_premultiplied

Get whether this color is premultiplied

Returns

boolean :

premultiplied

hex

Get this color represented as a hexademical string

Returns

string :

hex representation

Examples

var c = new mapnik.Color('green');
c.hex();
// '#008000'

set_premultiplied(premultiplied)

Set whether this color should be premultiplied

parameter type description
premultiplied boolean

Throws

exception description
TypeError

given a non-boolean argument

Examples

var c = new mapnik.Color('green');
c.set_premultiplied(true);

toString

Get this color's representation as a string

Returns

string :

color as a string

Examples

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

mapnik.Datasource

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

describe

Describe the datasource's contents and type.

Returns

Object :

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

extent

Get the Datasource's extent

mapnik.Feature

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

fromJSON(geojson)

parameter type description
geojson string

string

Create a feature from a GeoJSON representation.

attributes

Get the feature's attributes as an object.

Returns

Object :

attributes

extent

Get the feature's extent

Returns

Array<number> :

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

geometry

Get the feature's attributes as a Mapnik geometry.

Returns

mapnik.Geometry :

geometry

id

Returns

number :

id the feature's internal id

toJSON

Generate and return a GeoJSON representation of this feature

Returns

string :

geojson Feature object in stringified GeoJSON

mapnik.Featureset

An iterator of mapnik.Feature objects.

next

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

Returns

mapnik.Feature or :

next feature

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.

extent

Get the geometry's extent

Returns

Array<number> :

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

toJSON([options], callback)

Convert this geometry into a GeoJSON representation, asynchronously.

parameter type description
options [Object] (default {})

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

callback Function

called with (err, result)

toJSONSync

Convert this geometry into a GeoJSON representation, synchronously.

Returns

string :

GeoJSON, string-encoded representation of this geometry.

toWKB

Get the geometry's representation as Well-Known Binary

Returns

string :

wkb representation of this geometry

toWKT

Get the geometry's representation as Well-Known Text

Returns

string :

wkt representation of this geometry

type

Get the geometry type

Returns

string :

type of geometry.

mapnik.Grid(width, height, [options])

Generator for UTFGrid representations of data.

parameter type description
width number
height number
options [Object] (default {})

optional argument, which can have a 'key' property

property type description
key string

addField(field)

Add a field to this grid's output

parameter type description
field string

addField

Get all of this grid's fields

encodeSync([options])

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

parameter type description
options [Object] (default { resolution: 4, features: false })

Returns

Object :

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

height

Get this grid's height

Returns

number :

height

view(x, y, width, height)

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

parameter type description
x number
y number
width number
height number

Returns

mapnik.Grid :

a grid constrained to this new view

width

Get this grid's width

Returns

number :

width

mapnik.Image(width, height, [options])

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

parameter type description
width number

width in pixels

height number

height in pixels

options [Object]
options.type [Object] (default mapnik.imageType.rgb8)

a mapnik.imageType object

options.initialize [bool] (default true)
options.premultiplied [bool] (default false)
options.painted [bool] (default false)

property type description
offset number

offset number

scaling number

scaling number

Throws

exception description
TypeError

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

Examples

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

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!

parameter type description
width number
height number
buffer Buffer

Returns

mapnik.Image :

image object

Examples

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, callback)

Create an image from a byte stream buffer.

parameter type description
buffer Buffer

image buffer

callback Function

function(err, img)

Examples

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)

Create a new image from an SVG file

parameter type 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.

callback Function

Examples

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)

Load image from an SVG buffer

parameter type 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.

callback Function

= function(err, img)

Examples

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])

Load image from an SVG buffer (synchronous)

parameter type 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.

Returns

mapnik.Image :

Image object

Examples

var buffer = fs.readFileSync('./path/to/image.svg');
var img = mapnik.Image.fromSVGBytesSync(buffer);

fromSVGSync(filename, [options])

Create a new image from an SVG file (synchronous)

parameter type 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.

Returns

mapnik.Image :

image object

Examples

var img = mapnik.Image.fromSVG('./path/to/image.svg');

open(path, callback)

Load in a pre-existing image as an image object

parameter type description
path string

path to the image you want to load

callback Function

Examples

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

clear(callback)

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

parameter type description
callback Function

Examples

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

Make this image transparent. (synchronous)

Examples

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])

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().

parameter type description
image mapnik.Image

another mapnik.Image instance to compare to

options [Object]
options.threshold [number] (default 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 [bool] (default 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);

Examples

// 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)

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

parameter type 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

Examples

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)

Copy an image into a new image by creating a clone

parameter type description
type number

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

options [Object] (default {})
options.scaling [number]

scale the image

options.offset [number]

offset this image

callback Function

Examples

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])

Copy an image into a new image by creating a clone

parameter type description
type number

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

options [Object] (default {})
options.scaling [number]

scale the image

options.offset [number]

offset this image

Returns

mapnik.Image :

copy

Examples

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

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

Returns

Buffer :

pixel data as a buffer

Examples

var img = new mapnik.Image.open('./path/to/image.png');
var buffr = img.data();

demultiply(callback)

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

parameter type description
callback Function

demultiplySync

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

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

Encode this image into a buffer of encoded data

parameter type description
format [string] (default png)

image format

options [Object]
options.palette [mapnik.Palette]

mapnik.Palette object

callback Function

function(err, encoded)

Returns

Buffer :

encoded image data

Examples

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])

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

parameter type description
format [string] (default png)

image format

options [Object]
options.palette [mapnik.Palette]

mapnik.Palette object

Returns

Buffer :

buffer - encoded image data

Examples

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)

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

parameter type description
color mapnik.Color or number
callback Function

function(err, img)

Examples

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)

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

parameter type description
color mapnik.Color or number

Examples

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)

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

parameter type description
filter string

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

callback Function

function(err, img)

Examples

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)

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

parameter type description
filter string

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

Examples

var img = new mapnik.Image(5, 5);
img.filter('blur');
// your custom code with `img` having blur applied

fromBytesSync(buffer)

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

parameter type description
buffer Buffer

image buffer

Returns

mapnik.Image :

image object

Examples

var buffer = fs.readFileSync('./path/to/image.png');
var img = new mapnik.Image.fromBytesSync(buffer);

getPixel(x, y, [options])

Get a specific pixel and its value

parameter type 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 or Object :

color number or object of rgba values

Examples

// 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

Determine the image type

Returns

number :

Number of the image type

Examples

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

Get this image's height in pixels

Returns

number :

height

Examples

var img = new mapnik.Image(4,4);
console.log(img.height()); // 4

isSolid

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

Returns

bool :

true means all pixels are exactly the same

Examples

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

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

Returns

boolean :

whether the image is solid

Examples

var img = new mapnik.Image(256, 256);
var view = img.view(0, 0, 256, 256);
console.log(view.isSolidSync()); // true

openSync(path)

Load in a pre-existing image as an image object

parameter type description
path string

path to the image you want to load

Returns

mapnik.Image :

new image object based on existing image

Examples

var img = new mapnik.Image.open('./path/to/image.jpg');

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

bool :

whether it is painted or not

Examples

var img = new mapnik.Image(5,5);
console.log(img.painted()); // false

premultiplied

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

Returns

boolean :

premultiplied true if the image is premultiplied

Examples

var img = new mapnik.Image(5,5);
console.log(img.premultiplied()); // false
img.premultiplySync()
console.log(img.premultiplied()); // true

premultiply(callback)

Premultiply the pixels in this image, asynchronously

parameter type description
callback Function

Examples

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

premultiplySync

Premultiply the pixels in this image.

Examples

var img = new mapnik.Image(5,5);
img.premultiplySync();
console.log(img.premultiplied()); // true

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

Resize this image (makes a copy)

parameter type description
width number

in pixels

height number

in pixels

options [Object] (default {})
options.offset_x [number] (default 0)

offset the image horizontally in pixels

options.offset_y [number] (default 0)

offset the image vertically in pixels

options.scaling_method [mapnik.imageScaling] (default mapnik.imageScaling.near)

scaling method

options.filter_factor [number] (default 1.0)
callback Function

function(err, result)

Examples

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])

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

parameter type description
width number
height number
options [Object] (default {})
options.offset_x [number] (default 0)

offset the image horizontally in pixels

options.offset_y [number] (default 0)

offset the image vertically in pixels

options.scaling_method [mapnik.imageScaling] (default mapnik.imageScaling.near)

scaling method

options.filter_factor [number] (default 1.0)

Returns

mapnik.Image :

copy

Examples

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)

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

parameter type description
filename string
format [string] (default png)
callback Function

Examples

img.save('image.png', 'png', function(err) {
  if (err) throw err;
  // your custom code   
});

saveSync(filename, [format])

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

parameter type description
filename string
format [string] (default png)

Examples

img.saveSync('foo.png');

setGrayScaleToAlpha(color)

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

parameter type description
color mapnik.Color

Examples

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)

Set a pixels value

parameter type description
x number

position within image from top left

y number

position within image from top left

numeric Object or number

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

Examples

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)

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

parameter type description
x number
y number
width number
height number

Returns

mapnik.Image :

an image constrained to this new view

Examples

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

Get this image's width in pixels

Returns

number :

width

Examples

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

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

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

parameter type description
left number
top number
width number
height number

Throws

exception description
TypeError

if any argument is missing or not numeric

Examples

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

mapnik.Logger

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

Examples

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

get_severity

Returns integer which represents severity level

Returns

number :

severity level

set_severity(severity)

Accepts level of severity as a mapnik constant

Available security levels

mapnik.Logger.DEBUG -> 0
mapnik.Logger.WARN -> 1
mapnik.Logger.ERROR (default) -> 2
mapnik.Logger.NONE -> 3

parameter type description
severity number

severity level

Returns

number :

severity level

mapnik.Map(width, height, [projection])

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

parameter type description
width int

in pixels

height int

in pixels

projection [string] (default '+proj)

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

property type 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

add_layer(new)

Add a new layer to this map

parameter type description
new mapnik.Layer

layer

clear

Remove all layers and styles from this map

clone

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

Returns

mapnik.Map :

clone

font

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

Returns

Array<string> :

fonts

fontDirectory

Get the currently-registered font directory, if any

Returns

string or :

fonts

fontFiles

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

Returns

Object :

fonts

fromStringSync(stylesheet, [options])

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

parameter type description
stylesheet string

contents

options [Object] (default {})

Examples

var fs = require('fs');
map.fromStringSync(fs.readFileSync('./style.xml', 'utf8'));

fromStringSync(stylesheet, [options], callback)

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

parameter type description
stylesheet string

contents

options [Object] (default {})
callback Function

Examples

var fs = require('fs');
map.fromStringSync(fs.readFileSync('./style.xml', 'utf8'), function(err, res) {
  // details loaded
});

get_layer(layer)

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

parameter type description
layer string or number

name or index

Returns

mapnik.Layer :

the layer

Throws

exception description
Error

if index is incorrect or layer is not found

layers

Get all of the currently-added layers in this map

Returns

Array<mapnik.Layer> :

layers

load(stylesheet, [options], callback)

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

parameter type description
stylesheet string

path

options [Object] (default {})
callback Function

loadFonts

Load fonts from local or external source

loadSync(stylesheet, [options])

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

parameter type description
stylesheet string

path

options [Object] (default {})

Examples

map.loadSync('./style.xml');

resize(width, height)

Give this map new dimensions

parameter type description
width number
height number

scale

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

Returns

number :

scale

scaleDenominator

Get the map's scale denominator.

Returns

number :

scale denominator

mapnik.Projection(projection, [options])

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

parameter type description
projection string

projection as a proj4 definition string

options [Object] (default {lazy:false})

whether to lazily instantiate the data backing this projection.

Throws

exception description
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

Examples

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

forward

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

inverse

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

mapnik.VectorTile(z, x, y)

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

parameter type description
z number

an integer zoom level

x number

an integer x coordinate

y number

an integer y coordinate

property type 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

Examples

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

addData(buffer, callback)

Add new vector tile data to an existing vector tile

parameter type description
buffer Buffer

raw vector data

callback Object

Examples

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)

Add raw data to this tile as a Buffer

parameter type description
buffer Buffer

raw data

Examples

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)

Add features to this tile from a GeoJSON string

parameter type description
geojson string

as a string

name string

of the layer to be added

options Object
options.area_threshold [number] (default 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] (default 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 [bool] (default true)

ensure all geometry is valid according to OGC Simple definition

options.multi_polygon_union [bool] (default false)

union all multipolygons

options.fill_type [Object<mapnik.polygonFillType>] (default 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 [bool] (default false)

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

Examples

var geojson = { ... };
var vt = mapnik.VectorTile(0,0,0);
vt.addGeoJSON(JSON.stringify(geojson), 'layer-name', {});

addImage(image, name, [options])

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

parameter type description
image mapnik.Image
name string

of the layer to be added

options [Object]
options.image_scaling [string] (default bilinear)

can be any of the <mapnik.imageScaling> methods

options.image_format [string] (default webp)

other options include jpeg, png, tiff

Examples

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)

Add an encoded image buffer as a layer

parameter type description
buffer Buffer

raw image data

name string

name of the layer to be added

callback Function

Examples

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)

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

parameter type description
buffer Buffer

raw data

name string

name of the layer to be added

Examples

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)

Add a mapnik.Image as a tile layer (synchronous)

parameter type description
image mapnik.Image
name string

of the layer to be added

options Object
options.image_scaling [string] (default bilinear)

can be any of the <mapnik.imageScaling> methods

options.image_format [string] (default webp)

or jpeg, png, tiff

Examples

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

Get the extent including the buffer of this vector tile

Returns

Array<number> :

extent - [minx, miny, maxx, maxy]

Examples

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)

Remove all data from this vector tile

parameter type description
callback Function

Examples

vt.clear(function(err) {
  if (err) throw err;
  console.log(vt.getData().length); // 0   
});

clearSync

Remove all data from this vector tile (synchronously)

Examples

vt.clearSync();
console.log(vt.getData().length); // 0

composite(array, [options], callback)

Composite an array of vector tiles into one vector tile

parameter type description
array Array<mapnik.VectorTile>

an array of vector tile objects

options [object]
options.scale_factor [float] (default 1.0)
options.offset_x [number] (default 0)
options.offset_y [number] (default 0)
options.area_threshold [float] (default 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 [bool] (default true)

ensure all geometry is valid according to OGC Simple definition

options.multi_polygon_union [bool] (default false)

union all multipolygons

options.fill_type [Object<mapnik.polygonFillType>] (default 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] (default 0.0)
options.reencode [bool] (default false)
options.max_extent [Array<number>] (default minx,miny,maxx,maxy)
options.simplify_distance [float] (default 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 [bool] (default 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] (default webp)

or jpeg, png, tiff

options.scaling_method [string] (default bilinear)

can be any of the <mapnik.imageScaling> methods

options.threading_mode [string] (default deferred)
callback Function

function(err)

Examples

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])

Synchronous version of VectorTile#composite

parameter type description
array Array<mapnik.VectorTile>

an array of vector tile objects

options [object]

Examples

var vt1 = new mapnik.VectorTile(0,0,0);
var vt2 = new mapnik.VectorTile(0,0,0);
var options = { ... };
vt1.compositeSync([vt2], options);

empty

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

Returns

boolean :

whether the layer is empty

Examples

var vt = new mapnik.VectorTile(0,0,0);
var empty = vt.empty();
console.log(empty); // true

emptyLayers

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

Returns

Array<string> :

layer names

Examples

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

Get the extent of this vector tile

Returns

Array<number> :

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

Examples

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)

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

parameter type description
options [Object]
options.compression [string] (default none)

compression type can also be gzip

options.level [int] (default 0)

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

options.strategy string

must be FILTERED, HUFFMAN_ONLY, RLE, FIXED, DEFAULT

callback Function

Examples

vt.getData({
  compression: 'gzip',
  level: 9,
  strategy: 'FILTERED'
}, function(err, data) {
  if (err) throw err;
  console.log(data); // buffer
});

getDataSync([options])

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

parameter type description
options [Object]
options.compression [string] (default none)

can also be gzip

options.level [int] (default 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

Examples

var data = vt.getData({
  compression: 'gzip',
  level: 9,
  strategy: 'FILTERED'
});

names

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

Returns

Array<string> :

layer names

Examples

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

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

Examples

var vt = new mapnik.VectorTile(0,0,0);
var painted = vt.painted();
console.log(painted); // false

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

Examples

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)

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.

parameter type description
longitude number

longitude

latitude number

latitude

options [Object]
options.tolerance [number] (default 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

Examples

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])

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

parameter type description
array array<number>

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

options Object
options.tolerance [number] (default 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.

Examples

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)

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

parameter type 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 or 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

Examples

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)

Count the number of geometries that are not OGC simple

parameter type description
callback Function

Examples

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

Count the number of geometries that are not OGC simple

Returns

number :

number of features that are not simple

Examples

var simple = vectorTile.reportGeometrySimplicitySync();
console.log(simple); // array of non-simple geometries and their layer info
console.log(simple.length); // number

reportGeometryValidity(callback)

Count the number of geometries that are not OGC valid

parameter type description
callback Function

Examples

vectorTile.reportGeometryValidity(function(err, valid) {
  console.log(valid); // array of invalid geometries and their layer info
  console.log(valid.length); // number    
});

reportGeometryValiditySync

Count the number of geometries that are not OGC valid

Returns

number :

number of features that are not valid

Examples

var valid = vectorTile.reportGeometryValiditySync();
console.log(valid); // array of invalid geometries and their layer info
console.log(valid.length); // number

setData(buffer, callback)

Replace the data in this vector tile with new raw data

parameter type description
buffer Buffer

raw data

callback Function

Examples

var data = fs.readFileSync('./path/to/data.mvt');
vectorTile.setData(data, function(err) {
  if (err) throw err;
  // your custom code
});

setDataSync(buffer)

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

parameter type description
buffer Buffer

raw data

Examples

var data = fs.readFileSync('./path/to/data.mvt');
vectorTile.setDataSync(data);
// your custom code

toGeoJSON([layer], [index], callback)

Get a GeoJSON representation of this tile

parameter type description
layer [string or number] (default __all__)

Can be a custom layer name, __array__ of layer names, or __all__ for all layers.

index [number] (default 0)

Specify the layer index, cannot be greater than the number of layers in the vector tile

callback Function

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

Examples

vectorTile.toGeoJSON(function(err, geojson) {
  if (err) throw err;
  console.log(geojson); // stringified GeoJSON
  console.log(JSON.parse(geojson)); // GeoJSON object
});

toGeoJSONSync(layer, inded)

Syncronous version of VectorTile#toGeoJSON

parameter type description
layer string or number
inded number

Returns

string :

stringified GeoJSON of all the features in this tile.

Examples

var geojson = vectorTile.toGeoJSONSync();
geojson // stringified GeoJSON
JSON.parse(geojson); // GeoJSON object

toJSON([options])

Get a JSON representation of this tile

parameter type description
options [Object]
options.decode_geometry [bool] (default false)

return geometry as integers relative to the tile grid

Returns

Object :

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

Examples

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
// }

mapnik.blend

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