MazeMap / Leaflet.TileLayer.PouchDBCached

A Leaflet tile layer which caches into PouchDB for offline use
MIT License
207 stars 68 forks source link

Allows all Leaflet TileLayers to cache into PouchDB for offline use, in a transparent fashion.

There is a demo available, which shows cache hits/misses/seeds in the browser's developer console.

Dependencies

Tested with Leaflet 1.4.0 and PouchDB 7.0.0.

You probably want to load Leaflet, PouchDB and Leaflet.TileLayer.PouchDB like so:

    <script src="https://unpkg.com/leaflet@^1.0.0/dist/leaflet-src.js"></script>
    <script src="https://unpkg.com/pouchdb@^5.2.0/dist/pouchdb.js"></script>
    <script src="https://unpkg.com/leaflet.tilelayer.pouchdbcached@latest/L.TileLayer.PouchDBCached.js"></script>

If you are still using Leaflet 0.7.x, the latest compatible release is v0.1.0.

Usage

The plugin modifies the core L.TileLayer class, so it should be possible to cache any tile layer.

To use, add the option useCache with a value of true when instantiating your layer. You probably want to use Leaflet's crossOrigin option, like so:

var layer = L.tileLayer('https://whatever/{z}/{x}/{y}.png', {
    maxZoom: 18,

    useCache: true,
    crossOrigin: true
});

Options available are as follows:

New functions available are as follows:

New events available are as follows:

Cross-Origin Resource Sharing

Due to the tile images being parsed and stored by the browser (technically, extracting data from a canvas in which a external image has been loaded into), the tiles must come from a tile server which allows CORS (Cross-Origin Resource Sharing) on the tiles. So tiles must have a CORS header allowing them to be loaded in the document where you're using this caching layer.

In other words: if chrome shows a grey map, and displays CORS-related messages in the console, make sure that your tileserver adds this header to all tiles:

Access-Control-Allow-Origin: *

Underlying cache structure

This plugin uses an instance of PouchDB, named offline-tiles. PouchDB is a key-value store, so the key is the URL of a tile, and the value is a plain object containing a timestamp and the base64-encoded image.

License and stuff

Under MIT license.

Heavily inspired by https://github.com/tbicr/OfflineMap