-
Notifications
You must be signed in to change notification settings - Fork 33
/
app.js
executable file
·106 lines (90 loc) · 3.21 KB
/
app.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
99
100
101
102
103
104
105
106
#!/usr/bin/env node
// This example shows how to use node-mapnik with the
// connect http server to serve map tiles to polymaps
// client. Also logs tile render speed
//
// expected output at zoom 0: http://goo.gl/cyGwo
var mapnik = require('mapnik')
, mercator = require('../../utils/sphericalmercator')
, mappool = require('../../utils/pool.js')
, http = require('http')
, parseXYZ = require('../../utils/tile.js').parseXYZ;
// register shapefile plugin
if (mapnik.register_default_input_plugins) mapnik.register_default_input_plugins();
var TMS_SCHEME = false;
// create a pool of 5 maps to manage concurrency under load
var maps = mappool.create_pool(5);
var usage = 'usage: app.js <stylesheet> <port>\ndemo: app.js ../../stylesheet.xml 8000';
var stylesheet = process.argv[2];
if (!stylesheet) {
console.log(usage);
process.exit(1);
}
var port = process.argv[3];
if (!port) {
console.log(usage);
process.exit(1);
}
var aquire = function(id,options,callback) {
methods = {
create: function(cb) {
var obj = new mapnik.Map(options.width || 256, options.height || 256);
obj.load(id, {strict: true},function(err,obj) {
if (options.bufferSize) {
obj.bufferSize = options.bufferSize;
}
cb(err,obj);
});
},
destroy: function(obj) {
delete obj;
}
};
maps.acquire(id,methods,function(err,obj) {
callback(err, obj);
});
};
http.createServer(function(req, res) {
parseXYZ(req, TMS_SCHEME, function(err,params) {
if (err) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err.message);
} else {
aquire(stylesheet, {}, function(err, map) {
if (err) {
process.nextTick(function() {
maps.release(stylesheet, map);
});
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err.message);
} else {
// bbox for x,y,z
var bbox = mercator.xyz_to_envelope(params.x, params.y, params.z, TMS_SCHEME);
map.extent = bbox;
var im = new mapnik.Image(map.width, map.height);
map.render(im, function(err, im) {
process.nextTick(function() {
maps.release(stylesheet, map);
});
if (err) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(err.message);
} else {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(im.encodeSync('png'));
}
});
}
});
}
});
}).listen(port);
console.log('Test server listening on port %d', port);