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;
相关推荐
络71 天前
Redis 非缓存核心场景及实例说明
数据库·redis·缓存
土了个豆子的1 天前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
YUELEI1181 天前
langchain 缓存 Caching
缓存·langchain
孤独的人1 天前
WordPress 性能优化:从插件到 CDN 的全方位缓存设置指南
spring·缓存·性能优化
MAGICIAN...2 天前
【Redis】--持久化机制
数据库·redis·缓存
我真的是大笨蛋2 天前
JVM调优总结
java·jvm·数据库·redis·缓存·性能优化·系统架构
拾忆,想起2 天前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
破烂儿2 天前
基于机器学习的缓存准入策略研究
人工智能·机器学习·缓存
参.商.2 天前
【Day21】146.LRU缓存 (Least Recently Used)
leetcode·缓存·golang
Dorcas_FE2 天前
axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”
前端·spring·缓存