-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
98 lines (80 loc) · 2.64 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var mapnik = require('mapnik'),
path = require('path'),
fs = require('fs'),
zlib = require('zlib'),
mercator = new(require('sphericalmercator'))();
//mapnik.register_default_input_plugins();
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));
exports.generate = function( geojson, params, callback ) {
var size = params.size || 256;
var format = params.format;
var name = params.name || 'layer';
createStyleSheet( geojson, name, function(err, stylesheet){
if ( err ){
return callback(err, null);
}
map = new mapnik.Map(size, size);
map.fromStringSync( stylesheet );
map.extent = mercator.bbox(params.x, params.y, params.z, false, '900913');
if ( format == 'png' ){
var image = new mapnik.Image(size, size);
map.render( image, {}, function( err, im ) {
if (err) {
callback( err, null );
}
else {
im.encode( 'png', function( err, buffer ) {
callback( null, buffer );
});
}
});
}
else if (format == 'vector.pbf' || format == 'pbf') {
var vtile = new mapnik.VectorTile( params.z, params.x, params.y );
map.render( vtile, {}, function( err, vtile ) {
if (err) {
callback( err, null );
}
else {
zlib.deflate(vtile.getData(), function(err, buffer) {
callback( null, buffer );
});
}
});
} else if ( format == 'utf' ) {
var grid = new mapnik.Grid(size, size, {key: '__id__'});
map.render( grid, {layer: name}, function( err, g ) {
if (err) {
callback( err, null );
}
else {
g.encode({features: true, resolution: 4}, function (err, utf) {
callback(err, JSON.stringify(utf))
})
}
});
}
else {
callback( 'Unknown or missing file format', null );
}
});
};
// replace template strings with real data
var createStyleSheet = function(geojson, layerName, callback){
try {
var template = fs.readFileSync(__dirname + '/lib/stylesheet.xml', 'utf8');
var geom_type;
if (geojson && geojson.features && geojson.features[0] && geojson.features[0].geometry){
geom_type = geojson.features[0].geometry.type.toLowerCase();
} else {
geom_type = 'point';
}
template = template.replace('{{name}}', layerName);
template = template.replace('{{style}}', geom_type);
template = template.replace('{{geojson}}', JSON.stringify( geojson ) );
callback(null, template);
} catch(e) {
console.log(e);
callback('Could not create stylesheet', null);
}
}