/
thumbnail.js
67 lines (61 loc) · 1.97 KB
/
thumbnail.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
const mapnik = require('mapnik');
const sm = new (require('@mapbox/sphericalmercator'))();
const events = require('events');
if (mapnik.register_default_input_plugins) {
mapnik.register_default_input_plugins();
}
/**
* Create a new source that returns tiles from a Mapnik xml stylesheet template
* and a GeoJSON object.
* @private
* @param {object} GeoJSON object
* @param {function} callback
* @returns {undefined}
*/
class ThumbnailSource extends events.EventEmitter {
constructor(geojson, template, imageOptions, mapOptions) {
super();
this._size = imageOptions.tileSize || 256;
// see image encoding options: https://github.com/mapnik/mapnik/wiki/Image-IO
this._imageEncoding = imageOptions.encoding || 'png8:m=h:z=1';
this._bufferSize = 64;
this._mapOptions = mapOptions || {};
this._xml = template.replace('{{geojson}}', JSON.stringify(geojson));
this.stats = {
requested: 0,
rendered: 0
};
}
/**
* Gets a tile from this source.
*
* @param {number} z
* @param {number} x
* @param {number} y
* @param {function} callback
*/
getTile(z, x, y, callback) {
const encoding = this._imageEncoding;
const size = this._size;
const map = new mapnik.Map(size, size);
map.bufferSize = this._bufferSize;
try {
// TODO: It is not smart or performant to create a new mapnik instance for each tile rendering
this.stats.rendered += 1;
map.fromString(this._xml, this._mapOptions, function onMapLoaded(err) {
if (err) return callback(err);
map.extent = sm.bbox(x, y, z, false, '900913');
map.render(new mapnik.Image(size, size), {}, function onImageRendered(err, image) {
if (err) return callback(err);
image.encode(encoding, function onImageEncoded(err, encodedImage) {
callback(err, encodedImage);
});
});
});
} catch (e) {
callback(e);
}
}
}
exports.ThumbnailSource = ThumbnailSource;