/
L.TileLayer.PouchDBCached.js
211 lines (178 loc) · 5.9 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
L.TileLayer.addInitHook(function() {
if (!this.options.useCache) {
this._db = null;
this._canvas = null;
return;
}
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;
}
});
L.TileLayer.prototype.options.useCache = false;
L.TileLayer.prototype.options.saveToCache = true;
L.TileLayer.prototype.options.useOnlyCache = false;
L.TileLayer.prototype.options.cacheMaxAge = 24*3600*1000;
L.TileLayer.include({
// Overwrites L.TileLayer.prototype._loadTile
_loadTile: function(tile, tilePoint) {
tile._layer = this;
tile.onerror = this._tileOnError;
this._adjustTilePoint(tilePoint);
var tileUrl = this.getTileUrl(tilePoint);
this.fire('tileloadstart', {
tile: tile,
url: tileUrl
});
if (this.options.useCache && this._canvas) {
this._db.get(tileUrl, {revs_info: true}, this._onCacheLookup(tile,tileUrl));
} else {
// Fall back to standard behaviour
tile.onload = this._tileOnLoad;
tile.src = tileUrl;
}
},
// 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) {
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 = this._saveTile(tileUrl, data._revs_info[0].rev);
}
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 = this._tileOnLoad;
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 = this._tileOnLoad;
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 = this._saveTile(tileUrl);
} else {
tile.onload = this._tileOnLoad;
}
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(tileUrl, existingRevision) {
return function(ev) {
if (this._canvas === null) return;
var img = ev.target;
L.TileLayer.prototype._tileOnLoad.call(img,ev);
this._canvas.width = img.naturalWidth || img.width;
this._canvas.height = img.naturalHeight || img.height;
var context = this._canvas.getContext('2d');
context.drawImage(img, 0, 0);
var dataUrl = this._canvas.toDataURL('image/png');
var doc = {dataUrl: dataUrl, timestamp: Date.now()};
if (existingRevision) {
this._db.remove(tileUrl, existingRevision);
}
this._db.put(doc, tileUrl, doc.timestamp);
}.bind(this);
},
// Seeds the cache given a bounding box (latLngBounds), and
// the minimum and maximum zoom levels
// Use with care! This can spawn thousands of requests and
// flood tileservers!
seed: function(bbox, minZoom, maxZoom) {
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(
northEastPoint.divideBy(tileSize)._floor(),
southWestPoint.divideBy(tileSize)._floor());
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);
},
// 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) {
/// FIXME: Do something on tile error!!
tile.onload = function(ev){
this._saveTile(url)(ev);
this._seedOneTile(tile, remaining, seedData);
}.bind(this);
tile.crossOrigin = 'Anonymous';
tile.src = url;
} else {
this._seedOneTile(tile, remaining, seedData);
}
}.bind(this));
}
});