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;
相关推荐
Hello.Reader2 小时前
RedisJSON 路径语法深度解析与实战
数据库·redis·缓存
千宇宙航6 小时前
闲庭信步使用图像验证平台加速FPGA的开发:第十课——图像gamma矫正的FPGA实现
图像处理·计算机视觉·缓存·fpga开发
Alfred king9 小时前
面试150 LRU缓存
链表·缓存·哈希表·lru·双向链表
岸边的风11 小时前
退出登录后头像还在?这个缓存问题坑过多少前端!
前端·缓存·状态模式
Liudef0611 小时前
大模型KV缓存量化误差补偿机制:提升推理效率的关键技术
人工智能·缓存
在未来等你12 小时前
Redis面试精讲 Day 1:Redis核心特性与应用场景
数据库·redis·缓存·nosql·面试准备
Kookoos15 小时前
ABP VNext + 多级缓存架构:本地 + Redis + CDN
redis·缓存·微服务·架构·abp vnext
长风破浪会有时呀16 小时前
Redis 命令总结
数据库·redis·缓存
GDAL17 小时前
Node.js 聊天内容加密解密实战教程(含缓存密钥优化)
缓存·node.js
亚洲第一中锋_哈达迪17 小时前
详解缓存淘汰策略:LFU
后端·缓存·golang