Skip to content

Instantly share code, notes, and snippets.

@brentkirby
Created August 10, 2011 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentkirby/1138515 to your computer and use it in GitHub Desktop.
Save brentkirby/1138515 to your computer and use it in GitHub Desktop.
Serve .mbtiles with Rack
require File.expand_path('../../../config/application', __FILE__)
require 'rack'
require 'sqlite3'
module Rack
class MbTiles
attr_reader :app
def initialize(app)
@app = app
end
def dbpath
# path to db.mbtiles here
end
def call(env)
return app.call(env) unless env['PATH_INFO'].match(/mbtiles/)
options = env['PATH_INFO'].match(/mbtiles\/(.*)\/(.*)\/(.*).png$/i)
zoom, column, y = options[1], options[2], options[3]
puts dbpath.inspect
database = ::SQLite3::Database.new(dbpath)
rows = database.execute("select images.tile_data from map inner join images
on (map.tile_id = images.tile_id) where zoom_level = #{zoom} AND tile_row = #{y} AND tile_column = #{column}")
unless rows.empty?
[200, {"Content-Type" => "image/png"}, [rows[0][0]]]
else
[404, {}, [""]]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment