-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmbview.js
96 lines (80 loc) · 2.42 KB
/
mbview.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
/* eslint-disable no-console */
'use strict';
const express = require('express');
const app = express();
const MBTiles = require('@mapbox/mbtiles');
const q = require('d3-queue').queue();
const utils = require('./utils');
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
module.exports = {
/**
* Load a tileset and return a reference with metadata
* @param {object} file reference to the tileset
* @param {function} callback that returns the resulting tileset object
*/
loadTiles: function (file, callback) {
new MBTiles(file, ((err, tiles) => {
if (err) throw err;
tiles.getInfo((err, info) => {
if (err) throw err;
const tileset = Object.assign({}, info, {
tiles: tiles
});
callback(null, tileset);
});
}));
},
/**
* Defer loading of multiple MBTiles and spin up server.
* Will merge all the configurations found in the sources.
* @param {object} config for the server, e.g. port
* @param {function} callback with the server configuration loaded
*/
serve: function (config, callback) {
const loadTiles = this.loadTiles;
const listen = this.listen;
config.mbtiles.forEach((file) => {
q.defer(loadTiles, file);
});
q.awaitAll((error, tilesets) => {
if (error) throw error;
const finalConfig = utils.mergeConfigurations(config, tilesets);
listen(finalConfig, callback);
});
},
listen: function (config, onListen) {
const format = config.tiles._info.format;
app.get('/', (req, res) => {
if (format === 'pbf') {
res.render('vector', config);
} else {
res.render('raster', config);
}
});
app.get('/config', (req, res) => {
return res.json(config);
});
app.get('/:source/:z/:x/:y.' + format, (req, res) => {
const p = req.params;
const tiles = config.sources[p.source].tiles;
tiles.getTile(p.z, p.x, p.y, (err, tile, headers) => {
if (err) {
res.end();
} else {
res.writeHead(200, headers);
res.end(tile);
}
});
});
config.server = app.listen(config.port, config.host, () => {
onListen(null, config);
});
}
};