Skip to content

Instantly share code, notes, and snippets.

@manuelroth
Last active May 18, 2023 07:51
Show Gist options
  • Save manuelroth/8c03fe64bb2926e7f96e688c6bb1353c to your computer and use it in GitHub Desktop.
Save manuelroth/8c03fe64bb2926e7f96e688c6bb1353c to your computer and use it in GitHub Desktop.
A very simple node.js server for serving vector tiles from an mbtiles file
var express = require("express"),
app = express(),
MBTiles = require('mbtiles'),
p = require("path");
// Enable CORS and set correct mime type/content encoding
var header = {
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept",
"Content-Type":"application/x-protobuf",
"Content-Encoding":"gzip"
};
// Route which handles requests like the following: /<mbtiles-name>/0/1/2.pbf
app.get('/:source/:z/:x/:y.pbf', function(req, res) {
new MBTiles(p.join(__dirname, req.params.source + '.mbtiles'), function(err, mbtiles) {
mbtiles.getTile(req.params.z, req.params.x, req.params.y, function(err, tile, headers) {
if (err) {
res.set({"Content-Type": "text/plain"});
res.status(404).send('Tile rendering error: ' + err + '\n');
} else {
res.set(header);
res.send(tile);
}
});
if (err) console.log("error opening database");
});
});
// Starts up the server on port 3000
console.log('Listening on port: ' + 3000);
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment