UTFGrid and MBTiles map file decoding on Android

Patrick Y
2 min readAug 26, 2017

--

The following section discusses the problems, with regard to UTFGrid data inside of MBTiles file and solution.

Problem

We need to get the data of the grids for showing the popup window info and drawing the popup window on MapView when user tap a clickable grid, but MapBox Android Library doesn’t provide any functions for getting grid data from MBTile File(they provide the functions in their iOS and JavaScript SDK).

Solution

(Not-Completed, change to use OSMDroid SDK with OSMDroid SQLite map and GeoJSON format, please refer to OSMDroid)

We should find out the data and decode it from MBTiles file directly(without MapBox Android library) by ourselves.

Practice

Open the MBTiles file with SQLiteDatabase Class

SQLiteDatabase db = SQLiteDatabase.openDatabase(this.fileName, null, SQLiteDatabase.OPEN_READONLY);

Calculate the tile_row, tile_column, zoom_level with the coordinate which user tap. we can get the coordinate from MapView with mapView.getZoomLevel(), mapView.getLatitude(), mapView.getLongitude() (These methods are MapView built-in methods), and then use the specific algorithm to calculate it. And also you can find the formula below:

Here is the structure of the TilePosition

Use tile_row, tile_column, zoom_level to get BLOB data of UTFGrid field(field’s name is ‘grid’ in the view ‘grids’ in MBTiles file)

Once we get BLOB data, we should decompress the data with Zlib library, because the BLOB data is gzipped byte code

Convert BLOB data to JSON object

JSONObject utfGridJSON = new JSONObject(new String(utfGrid));JSONArray grid = utfGridJSON.getJSONArray("grid");JSONArray keys = utfGridJSON.getJSONArray("keys");

Calculate X and Y(starting from top left at 0 on the specified tile) from global coordinate for the click point

Resources

MbTiles definition
MbTiles specification
How Interactivity Works with UTFGrid
Specification for UTFGrid

Follow me at medium if you like this post ;-)

--

--

Patrick Y

Architecture, Android development, Functional programming