forked from nikolauskrismer/Leaflet.TileLayer.PouchDBCached
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathL.TileLayer.PouchDBCached.js
279 lines (240 loc) · 8.53 KB
/
L.TileLayer.PouchDBCached.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
L.TileLayer.addInitHook(function() {
if (!this.options.useCache) {
this._db = null;
this._canvas = null;
return;
}
if (this.options.dbOptions) {
this._db = new PouchDB('offline-tiles', this.options.dbOptions);
} else {
this._db = new PouchDB('offline-tiles');
}
this._canvas = document.createElement('canvas');
if (!(this._canvas.getContext && this._canvas.getContext('2d'))) {
// HTML5 canvas is needed to pack the tiles as base64 data. If
// the browser doesn't support canvas, the code will forcefully
// skip caching the tiles.
this._canvas = null;
}
});
// 🍂namespace TileLayer
// 🍂section PouchDB tile caching options
// 🍂option useCache: Boolean = false
// Whether to use a PouchDB cache on this tile layer, or not
L.TileLayer.prototype.options.useCache = false;
// 🍂option saveToCache: Boolean = true
// When caching is enabled, whether to save new tiles to the cache or not
L.TileLayer.prototype.options.saveToCache = true;
// 🍂option useOnlyCache: Boolean = false
// When caching is enabled, whether to request new tiles from the network or not
L.TileLayer.prototype.options.useOnlyCache = false;
// 🍂option useCache: String = 'image/png'
// The image format to be used when saving the tile images in the cache
L.TileLayer.prototype.options.cacheFormat = 'image/png';
// 🍂option cacheMaxAge: Number = 24*3600*1000
// Maximum age of the cache, in milliseconds
L.TileLayer.prototype.options.cacheMaxAge = 24*3600*1000;
L.TileLayer.include({
// Overwrites L.TileLayer.prototype.createTile
createTile: function(coords, done) {
var tile = document.createElement('img');
tile.onerror = L.bind(this._tileOnError, this, done, tile);
if (this.options.crossOrigin) {
tile.crossOrigin = '';
}
/*
Alt tag is *set to empty string to keep screen readers from reading URL and for compliance reasons
http://www.w3.org/TR/WCAG20-TECHS/H67
*/
tile.alt = '';
var tileUrl = this.getTileUrl(coords);
if (this.options.useCache && this._canvas) {
this._db.get(tileUrl, {revs_info: true}, this._onCacheLookup(tile, tileUrl, done));
} else {
// Fall back to standard behaviour
tile.onload = L.bind(this._tileOnLoad, this, done, tile);
}
tile.src = tileUrl;
return tile;
},
// Returns a callback (closure over tile/key/originalSrc) to be run when the DB
// backend is finished with a fetch operation.
_onCacheLookup: function(tile, tileUrl, done) {
return function(err, data) {
if (data) {
this.fire('tilecachehit', {
tile: tile,
url: tileUrl
});
if (Date.now() > data.timestamp + this.options.cacheMaxAge && !this.options.useOnlyCache) {
// Tile is too old, try to refresh it
//console.log('Tile is too old: ', tileUrl);
if (this.options.saveToCache) {
tile.onload = L.bind(this._saveTile, this, tile, tileUrl, data._revs_info[0].rev, done);
}
tile.crossOrigin = 'Anonymous';
tile.src = tileUrl;
tile.onerror = function(ev) {
// If the tile is too old but couldn't be fetched from the network,
// serve the one still in cache.
this.src = data.dataUrl;
}
} else {
// Serve tile from cached data
//console.log('Tile is cached: ', tileUrl);
tile.onload = L.bind(this._tileOnLoad, this, done, tile);
tile.src = data.dataUrl; // data.dataUrl is already a base64-encoded PNG image.
}
} else {
this.fire('tilecachemiss', {
tile: tile,
url: tileUrl
});
if (this.options.useOnlyCache) {
// Offline, not cached
// console.log('Tile not in cache', tileUrl);
tile.onload = L.Util.falseFn;
tile.src = L.Util.emptyImageUrl;
} else {
//Online, not cached, request the tile normally
// console.log('Requesting tile normally', tileUrl);
if (this.options.saveToCache) {
tile.onload = L.bind(this._saveTile, this, tile, tileUrl, null, done);
} else {
tile.onload = L.bind(this._tileOnLoad, this, done, tile);
}
tile.crossOrigin = 'Anonymous';
tile.src = tileUrl;
}
}
}.bind(this);
},
// Returns an event handler (closure over DB key), which runs
// when the tile (which is an <img>) is ready.
// The handler will delete the document from pouchDB if an existing revision is passed.
// This will keep just the latest valid copy of the image in the cache.
_saveTile: function(tile, tileUrl, existingRevision, done) {
if (this._canvas === null) return;
this._canvas.width = tile.naturalWidth || tile.width;
this._canvas.height = tile.naturalHeight || tile.height;
var context = this._canvas.getContext('2d');
context.drawImage(tile, 0, 0);
var dataUrl;
try {
dataUrl = this._canvas.toDataURL(this.options.cacheFormat);
} catch(err) {
this.fire('tilecacheerror', { tile: tile, error: err });
return done();
}
var doc = {_id: tileUrl, dataUrl: dataUrl, timestamp: Date.now()};
if (existingRevision) {
this._db.get(tileUrl).then(function(doc) {
return this._db.put({
_id: doc._id,
_rev: doc._rev,
dataUrl: dataUrl,
timestamp: Date.now()
});
}.bind(this)).then(function(response) {
//console.log('_saveTile update: ', response);
});
} else {
this._db.put(doc).then( function(doc) {
//console.log('_saveTile insert: ', doc);
});
}
if (done) {
done();
}
},
// 🍂section PouchDB tile caching options
// 🍂method seed(bbox: LatLngBounds, minZoom: Number, maxZoom: Number): this
// Starts seeding the cache given a bounding box and the minimum/maximum zoom levels
// Use with care! This can spawn thousands of requests and flood tileservers!
seed: function(bbox, minZoom, maxZoom) {
if (!this.options.useCache) return;
if (minZoom > maxZoom) return;
if (!this._map) return;
var queue = [];
for (var z = minZoom; z<=maxZoom; z++) {
var northEastPoint = this._map.project(bbox.getNorthEast(),z);
var southWestPoint = this._map.project(bbox.getSouthWest(),z);
// Calculate tile indexes as per L.TileLayer._update and
// L.TileLayer._addTilesFromCenterOut
var tileSize = this.getTileSize();
var tileBounds = L.bounds(
L.point(Math.floor(northEastPoint.x / tileSize.x), Math.floor(northEastPoint.y / tileSize.y)),
L.point(Math.floor(southWestPoint.x / tileSize.x), Math.floor(southWestPoint.y / tileSize.y)));
for (var j = tileBounds.min.y; j <= tileBounds.max.y; j++) {
for (var i = tileBounds.min.x; i <= tileBounds.max.x; i++) {
point = new L.Point(i, j);
point.z = z;
queue.push(this._getTileUrl(point));
}
}
}
var seedData = {
bbox: bbox,
minZoom: minZoom,
maxZoom: maxZoom,
queueLength: queue.length
}
this.fire('seedstart', seedData);
var tile = this._createTile();
tile._layer = this;
this._seedOneTile(tile, queue, seedData);
return this;
},
_createTile: function () {
return new Image();
},
// Modified L.TileLayer.getTileUrl, this will use the zoom given by the parameter coords
// instead of the maps current zoomlevel.
_getTileUrl: function (coords) {
var zoom = coords.z;
if (this.options.zoomReverse) {
zoom = this.options.maxZoom - zoom;
}
zoom += this.options.zoomOffset;
return L.Util.template(this._url, L.extend({
r: this.options.detectRetina && L.Browser.retina && this.options.maxZoom > 0 ? '@2x' : '',
s: this._getSubdomain(coords),
x: coords.x,
y: this.options.tms ? this._globalTileRange.max.y - coords.y : coords.y,
z: this.options.maxNativeZoom ? Math.min(zoom, this.options.maxNativeZoom) : zoom
}, this.options));
},
// Uses a defined tile to eat through one item in the queue and
// asynchronously recursively call itself when the tile has
// finished loading.
_seedOneTile: function(tile, remaining, seedData) {
if (!remaining.length) {
this.fire('seedend', seedData);
return;
}
this.fire('seedprogress', {
bbox: seedData.bbox,
minZoom: seedData.minZoom,
maxZoom: seedData.maxZoom,
queueLength: seedData.queueLength,
remainingLength: remaining.length
});
var url = remaining.pop();
this._db.get(url, function(err, data) {
if (!data) {
tile.onload = function(e) {
this._saveTile(tile, url, null);
this._seedOneTile(tile, remaining, seedData);
}.bind(this);
tile.onerror = function(e) {
// Could not load tile, let's continue anyways.
this._seedOneTile(tile, remaining, seedData);
}.bind(this);
tile.crossOrigin = 'Anonymous';
tile.src = url;
} else {
this._seedOneTile(tile, remaining, seedData);
}
}.bind(this));
}
});