Friday, May 30, 2014

Offline Mapping with Phonegap Build and mbTiles

Guest post by SilviaTerra intern Jim Miller


One of SilviaTerra's most popular products is Plot Hound, but navigating and mapping becomes tricky when you're deep in the woods without a data connection.

A little over a year ago, this post was created to shed some light on a possible solution where map tiles could be stored locally and then displayed in an HTML5 Mobile App, but it wasn't all that we were hoping for.

Ideally, the map tiles wouldn't be stored in a raw, uncompressed format on the local file system; instead, they could be efficiently stored in an mbTiles database. We wanted something similar to Scott Davis's solution to the problem: accessing an mbTiles database with tiles from MapBox with the Cordova SQLite Plugin and a custom Leaflet Tile Adapter. The dilemma was that there was no supported SQLite plugin for Phonegap Build, so to read an mbTiles database would mean sacrificing the hassle-free compiling and building that Phonegap Build does so nicely.

Finally, with Phonegap Build's feature to add your own plugin, we were able to submit a forked version of Brodysoft's Cordova SQLite plugin with a tweaked plugin.xml to get it to Build's standards. If you are interested in using an SQLite plugin for Android and iOS, feel free to grab his here. This allows us to access an mbTiles database stored on the phone rather than downloading individual tiles. All that was left to do was get the database to the phone and to display the tiles on a map (using a custom TileLayer).

This is the Phonegap app for Android that we made, integrating all of these processes together, and here is the source (most of the work is done in js/main.js).

A few notes on key steps to the final product: The SQLite plugin specifically looks for databases inside /data/data/{your package name}/databases, and because of this we used a few preferences in config.xml to make sure we were always saving to the internal file system of the Android device with the Phonegap FileTransfer API. And a special shout out to Scott Davis again: his custom TileLayer is the basis for js/TileLayer.MBTiles.js with a few modifications to account for a different SQLite plugin.

We're looking forward to integrating this proof-of-concept into Plot Hound in the coming month. Look for future updates on how we continue to develop HTML5 offline mapping technologies.