?//通過安裝包localforage(npm install localforage)或https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js
?tileCacheStore.js
import localforage from 'localforage'
var tileCacheStore=null;// 從緩存中獲取該瓦片
function loadFromCache(src) {if(tileCacheStore===null){
//通過安裝包localforage(npm install localforage)或https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.jstileCacheStore = localforage.createInstance({name: "tileCacheStore",//設置數據庫名稱driver: localforage.INDEXEDDB,//使用瀏覽器內置IndexDB數據庫});}return tileCacheStore.getItem(src);
}// 將該瓦片緩存
function cacheTile(src, img) {tileCacheStore.setItem(src, img)
}
// 觸發重試的錯誤碼
const retryCodes = [400, 500];
const retries = {};//瓦片加載事件
const wmtsTileLoadFunction = function(imageTile, src) {const image = imageTile.getImage();// 檢查緩存中是否已經存在該瓦片loadFromCache(src).then((tileCache) =>{if (tileCache!=null) {// 如果已經存在,直接使用緩存的瓦片替換圖片瓦片const imageUrl = URL.createObjectURL(tileCache);image.src = imageUrl;// image.src = tileCache;console.log("命中瓦片緩存")return;} else {fetch(src, {method: 'GET',keepalive: true,cache: "force-cache"}).then((response) => {if (retryCodes.includes(response.status)) {retries[src] = (retries[src] || 0) + 1;if (retries[src] < 3) {console.log("請求瓦片失敗,重新嘗試次數:" + retries[src])setTimeout(() => imageTile.load(), retries[src] * 250);}return Promise.reject();}return response.blob();}).then((blob) => {const imageUrl = URL.createObjectURL(blob);image.src = imageUrl;cacheTile(src, blob);}).catch(() => imageTile.setState(3)); // error}})};export default wmtsTileLoadFunction;
引入使用:
switch (mapLayer.layerType) {case 'XYZ':layer = new Tile({preload: Infinity,zIndex: mapLayer.zIndex,name: mapLayer.name,title: mapLayer.title,visible: mapLayer.visible,source: new XYZ({url: mapLayer.layerUrl,params: mapLayer.params,projection: mapLayer.projection}),params: mapLayer.params,});layer.getSource().setTileLoadFunction(wmtsTileLoadFunction)break;