Skip to content

Instantly share code, notes, and snippets.

@isedwards
Created August 8, 2013 13:54
Show Gist options
  • Save isedwards/6184779 to your computer and use it in GitHub Desktop.
Save isedwards/6184779 to your computer and use it in GitHub Desktop.
Add to lib/cartopy/io/img_tiles.py to enable loading image tiles from an MBTiles file. Unfortunately the demo (see comments below) does not currently work due to new bug: https://github.com/SciTools/cartopy/issues/312
class MBTiles(GoogleTiles):
''' Retrieve tile data from MBTiles sqlite database instead of a url '''
def __init__(self, tile_db):
self.tile_db = tile_db
GoogleTiles.__init__(self)
def get_image(self, tile):
import cStringIO
import sqlite3
x, y, z = tile
sql_select = ('select zoom_level, tile_column, tile_row, tile_data' +
' from tiles')
sql_where = 'where zoom_level=%s and tile_column=%s and tile_row=%s;' \
% (z, x, y)
con = sqlite3.connect(self.tile_db)
tiles = con.execute(sql_select + ' ' + sql_where)
tile_from_db = tiles.fetchone()
try:
im_data = tile_from_db[3]
except TypeError:
raise TypeError('No image data available for requested tile')
img = Image.open(cStringIO.StringIO(im_data))
img = img.convert(self.desired_tile_form)
return img, self.tileextent(tile), 'lower'
@isedwards
Copy link
Author

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import img_tiles

ax = plt.axes(projection=ccrs.Mercator())
tiles = img_tiles.MBTiles('osmbright.mbtiles')
ax.add_image(tiles, 8)
plt.show()

@bblay
Copy link

bblay commented Aug 14, 2013

Cartopy sends a Google tile index, but the database uses TMS indexing.

@bblay
Copy link

bblay commented Aug 14, 2013

Easy fix: y = (1 << z) - y - 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment