diff --git a/lib/mbtiles.js b/lib/mbtiles.js index 60e0201..b938417 100644 --- a/lib/mbtiles.js +++ b/lib/mbtiles.js @@ -29,14 +29,20 @@ function MBTiles(uri, callback) { if (typeof uri === 'string') uri = url.parse(uri); this.filename = uri.pathname; - this.db = new sqlite3.cached.Database(mbtiles.filename, function(err) { + Step(function() { + mbtiles.db = new sqlite3.cached.Database(mbtiles.filename, this) + }, function(err) { if (err) return callback(err); - else fs.stat(mbtiles.filename, function(err, stat) { - if (err) return callback(err); - mbtiles.stat = stat; - callback(null, mbtiles); - }); - }); + fs.stat(mbtiles.filename, this); + }, function(err, stat) { + if (err) return callback(err); + mbtiles.stat = stat; + mbtiles.exists('map', this); + }, function(err, exists) { + if (err) return callback(err); + else if (!exists) mbtiles.setup(this); + else this(null); + }, callback); }; // Finds all mbtiles file in the filepath and returns their tilesource URI. @@ -154,7 +160,17 @@ MBTiles.prototype.insertMetadata = function(data, callback) { this.insert('metadata', metadata, callback); }; -// Insert a set of tiles into an mbtiles database. +// Insert a tile. Scheme is XYZ. +MBTiles.prototype.putTile = function(z, x, y, data, callback) { + if (typeof callback !== 'function') callback = noop; + + // Flip Y coordinate because MBTiles files are TMS. + y = Math.pow(2, z) - 1 - y; + + this.insertTiles([ { z: z, x: x, y: y, data: data }], callback); +}; + +// Insert a set of tiles into an mbtiles database. Scheme is TMS. // // - @param {Array} renders array of images to be inserted. Each item should // be an object of the form { z: z, x: x, y: y, data: [Image buffer] }.