Skip to content

Instantly share code, notes, and snippets.

@jbaranski
Created August 1, 2020 14:52
Show Gist options
  • Save jbaranski/0073f7b98bdf1f64f49988853daed67b to your computer and use it in GitHub Desktop.
Save jbaranski/0073f7b98bdf1f64f49988853daed67b to your computer and use it in GitHub Desktop.
Convert an image (like JPG or TIF) to MBTiles using GDAL

Here are the steps needed to convert an image (like JPG or TIF) to MBTiles using GDAL:

  1. Download and install GDAL (https://gdal.org/, https://anaconda.org/conda-forge/gdal):

       conda install -c conda-forge gdal
    

    Installing GDAL is kind of a pain in the ass, especially on Windows. I'm assuming you'll be able to work out whatever issues you run into here.

  2. Download example jpg and tif map images we can work with:

  3. If you're starting with a jpg, first convert it to tif. To accomplish this run (replacing jpg and tif file names where necessary):

        gdal_translate -a_srs WGS84 -a_ullr -180 +90 +180 -90 map_1.jpg map_1.tif
    
  4. To convert tif to mbtiles run (replacing tif and mbtiles file names where necessary):

    
        gdal_translate -co "ZLEVEL=9" -of mbtiles map_1.tif map_1.mbtiles
        gdaladdo -r nearest map_1.mbtiles
    

    The first command lets GDAL figure out the max zoom it can generate based on the image resolution. The second command lets GDAL figure out and generate the lesser zoom levels based on the max zoom level that already exists. It's not uncommon for those two commands to take a while to complete.

  5. You can open the generated mbtiles file using a SQLite GUI or programmatically connect to it via a SQLite driver to inpsect and verify the content is correct (the spec can be found https://github.com/mapbox/mbtiles-spec/blob/master/1.2/spec.md).

  6. Now you need to serve your tiled map data. Here is one way to accomplish this:

        docker run -d -p 80:80 --name tileserver-php -v /d/mbtiles:/var/www/ klokantech/tileserver-php
    

    The volume should map to the location where all your mbtiles files sit. If you wish, you can get better performance by extracting the .mbtiles files out of the database onto the file system (if you have the disc space).

    You can now wire up a https://leafletjs.com/ client to your server. The url for the tile layer you feed into Leaflet would be http://localhost:80/map_1/{z}/{x}/{y}.png

  7. If you find tileserver-php 304's your requests when it shouldn't, just modify the isModified function in tileserver.php to always return FALSE (see maptiler/tileserver-php#148).

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