first stab at online tiles

This commit is contained in:
Konstantin Käfer
2011-06-21 21:45:38 +02:00
parent 6fe47f5fa9
commit c5660f598d
4 changed files with 96 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ var _ = require('underscore'),
Step = require('step'),
crypto = require('crypto'),
zlib = require('zlib'),
get = require('get'),
sqlite3 = require('sqlite3');
// MBTiles
@@ -10,8 +11,16 @@ var _ = require('underscore'),
// MBTiles class for doing common operations (schema setup, tile reading,
// insertion, etc.)
function MBTiles(filename, callback) {
var mbtiles = this;
this.filename = filename;
this.db = new sqlite3.Database(filename, callback);
this.db = new sqlite3.Database(filename, function(err) {
if (err) return callback(err);
mbtiles.metadata('online', function(err, value) {
// Ignore not-existant key.
mbtiles.online = value;
if (callback) callback(null);
});
});
};
// Retrieve the schema of the current mbtiles database and inform the caller of
@@ -208,16 +217,39 @@ MBTiles.prototype.insertGridTiles = function(map, callback) {
// - @param {Number} z tile z coordinate.
// - @param {Function} callback
MBTiles.prototype.tile = function(x, y, z, callback) {
var mbtiles = this;
this.db.get('SELECT tile_data FROM tiles WHERE ' +
'zoom_level = ? AND tile_column = ? AND tile_row = ?',
z, x, y,
function(err, row) {
if (err) callback(err);
else if (!row || !row.tile_data) callback(new Error('Tile does not exist'));
else if (!row || !row.tile_data) mbtiles.onlineTile(x, y, z, callback);
else callback(null, row.tile_data);
});
};
// Requests a tile from an online source and cache it to the database.
//
// - @param {Number} x tile x coordinate.
// - @param {Number} y tile y coordinate.
// - @param {Number} z tile z coordinate.
// - @param {Function} callback
MBTiles.prototype.onlineTile = function(x, y, z, callback) {
var mbtiles = this;
if (!this.online) {
return callback(new Error('Tile does not exist'));
}
var url = this.online.replace(/%x/g, x).replace(/%y/g, Math.pow(2, z) - 1 - y).replace(/%z/g, z);
new get(url).asBuffer(function(err, result) {
if (err) return callback(new Error(err));
// Cache image.
mbtiles.insertTiles([{ x: x, y: y, z: z, data: result }], function() {});
callback(null, result);
});
};
// Select a grid and its data from an mbtiles database.
//
// - @param {Number} x tile x coordinate