openlayers地图缓存添加

//通过安装包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.js
    tileCacheStore = 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;
相关推荐
码农飞哥7 分钟前
互联网大厂Java面试实战:Spring Boot到微服务的技术问答解析
java·数据库·spring boot·缓存·微服务·消息队列·面试技巧
scdifsn1 小时前
动手学深度学习12.4.硬件-笔记&练习(PyTorch)
pytorch·笔记·深度学习·缓存·内存·硬盘·深度学习硬件
寻找沙漠的人4 小时前
Redis 缓存
数据库·redis·缓存
LLLLLindream6 小时前
Redis——达人探店
数据库·redis·缓存
Clockwiseee7 小时前
RCE联系
数据库·redis·缓存·web
添砖Java中7 小时前
深入剖析缓存与数据库一致性:Java技术视角下的解决方案与实践
java·数据库·spring boot·spring·缓存·双写一致性
AllenO.o1 天前
Redis五种数据结构详解
java·数据结构·数据库·redis·缓存
yy鹈鹕灌顶1 天前
Redis 基础详解:从入门到精通
数据库·redis·缓存
程序员buddha2 天前
【代码优化篇】强缓存和协商缓存
缓存
我可是ikun啊2 天前
Redis经典面试题
数据库·redis·缓存