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;
相关推荐
添砖java‘’2 小时前
Redis中常用数据结构
数据库·redis·缓存
玛丽莲茼蒿7 小时前
Redis(六)—— Redis高级
数据库·redis·缓存
Wang's Blog8 小时前
PostgreSQL笔记27: 双缓存架构下的内存管理与性能观测实践
笔记·缓存·postgresql
WWJA王文举9 小时前
# STM32使用DMA后数据异常?可能不是DMA配置问题:从缓存、变量类型、时序到外设状态全面排查
stm32·嵌入式硬件·缓存
lv__pf1 天前
redis【msb 2026金三银四redis上】
数据库·redis·缓存
霸道流氓气质1 天前
Redis Pub/Sub — 概念、原理、场景与代码示例
数据库·redis·缓存
钱栈up1 天前
数据开放服务 Redis 缓存架构设计:从腹稿到落地方案
数据库·redis·缓存
夕除1 天前
redis--002
数据库·redis·缓存
xixiaoyunya1 天前
Redis 缓存三大经典问题深度解析:穿透、击穿、雪崩的原理与实战解决方案
spring boot·redis·缓存
dadaobusi1 天前
linux7.2-CAS-llc缓存感知
缓存