Do not cache data from aborted tile loads

This also results in a simplified cache method that can more easily be
overridden for use with other storage providers.
This commit is contained in:
ahocevar
2012-10-12 14:06:08 +02:00
parent cf3ea0c7db
commit 6607bcc0bb
3 changed files with 48 additions and 29 deletions

View File

@@ -111,7 +111,7 @@ OpenLayers.Control.CacheWrite = OpenLayers.Class(OpenLayers.Control, {
addLayer: function(evt) {
evt.layer.events.on({
tileloadstart: this.makeSameOrigin,
tileloaded: this.cache,
tileloaded: this.onTileloaded,
scope: this
});
},
@@ -128,7 +128,7 @@ OpenLayers.Control.CacheWrite = OpenLayers.Class(OpenLayers.Control, {
removeLayer: function(evt) {
evt.layer.events.un({
tileloadstart: this.makeSameOrigin,
tileloaded: this.cache,
tileloaded: this.onTileloaded,
scope: this
});
},
@@ -156,6 +156,22 @@ OpenLayers.Control.CacheWrite = OpenLayers.Class(OpenLayers.Control, {
}
},
/**
* Method: onTileloaded
* Decides whether a tile can be cached and calls the cache method.
*
* Parameters:
* evt - {Event}
*/
onTileloaded: function(evt) {
if (this.active && !evt.aborted &&
evt.tile instanceof OpenLayers.Tile.Image &&
evt.tile.url.substr(0, 5) !== 'data:') {
this.cache({tile: evt.tile});
delete OpenLayers.Control.CacheWrite.urlMap[evt.tile.url];
}
},
/**
* Method: cache
* Adds a tile to the cache. When the cache is full, the "cachefull" event
@@ -166,29 +182,25 @@ OpenLayers.Control.CacheWrite = OpenLayers.Class(OpenLayers.Control, {
* <OpenLayers.Tile.Image> with the data to add to the cache
*/
cache: function(obj) {
if (this.active && window.localStorage) {
if (window.localStorage) {
var tile = obj.tile;
if (tile instanceof OpenLayers.Tile.Image &&
tile.url.substr(0, 5) !== 'data:') {
try {
var canvasContext = tile.getCanvasContext();
if (canvasContext) {
var urlMap = OpenLayers.Control.CacheWrite.urlMap;
var url = urlMap[tile.url] || tile.url;
window.localStorage.setItem(
"olCache_" + url,
canvasContext.canvas.toDataURL(this.imageFormat)
);
delete urlMap[tile.url];
}
} catch(e) {
// local storage full or CORS violation
var reason = e.name || e.message;
if (reason && this.quotaRegEx.test(reason)) {
this.events.triggerEvent("cachefull", {tile: tile});
} else {
OpenLayers.Console.error(e.toString());
}
try {
var canvasContext = tile.getCanvasContext();
if (canvasContext) {
var urlMap = OpenLayers.Control.CacheWrite.urlMap;
var url = urlMap[tile.url] || tile.url;
window.localStorage.setItem(
"olCache_" + url,
canvasContext.canvas.toDataURL(this.imageFormat)
);
}
} catch(e) {
// local storage full or CORS violation
var reason = e.name || e.message;
if (reason && this.quotaRegEx.test(reason)) {
this.events.triggerEvent("cachefull", {tile: tile});
} else {
OpenLayers.Console.error(e.toString());
}
}
}