如何使用“开放层"下载,存储和加载图块? [英] How to download, store and load tiles using Open Layers?

查看:132
本文介绍了如何使用“开放层"下载,存储和加载图块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用开放层"创建PWA.用户必须选择在Wifi上下载磁贴以将其离线加载.我阅读了Open Layers文档,但是找不到我的问题的答案. 瓦片缓存部分为空.

I'm creating a PWA using Open Layers. The user must have an option to download the Tiles on the Wifi to load them Offline. I read the Open Layers documentation, but, I couldn't find the answer for my problem. The section Tile Cache is empty.

推荐答案

要使其正常工作,您需要做两件事:

You'll need two things for this to work:

  1. 用于存储图块的IndexedDB
  2. 自定义图块来源的自定义tileLoadFunction
  3. 一个用于下载给定范围的图块的组件

对于(1),您需要设置一家商店,例如tiles.下面的代码段使用了idb软件包( https://npmjs.com/package/idb ):

For (1), you'll want to set up a store, e.g. tiles. The snippet below uses the idb package (https://npmjs.com/package/idb):

import idb from 'idb';

let indexedDb;

idb.open(this.name, 1, upgradeDb => {
  if (!upgradeDb.objectStoreNames.contains('tiles')) {
    upgradeDb.createObjectStore('tiles');
  }
}).then(db => {
  indexedDb = db;
});

对于(2),起点可能看起来像这样:

For (2), a starting point could look something like this:

source.setTileLoadFunction(function(tile, url) {
  const tx = db.transaction('tiles', 'readonly');
  tiles = tx.objectStore('tiles');
  const image = tile.getImage();

  tiles.get(url).then(blob => {
    if (!blob) {
      // use online url
      image.src = url;
      return;
    }
    const objUrl = URL.createObjectURL(blob);
    image.onload = function() {
      URL.revokeObjectURL(objUrl);
    };
    image.src = objUrl;
  }).catch(() => {
    // use online url
    image.src = url;
  });
}

对于(3),您可能会希望在较小程度上限制下载.然后,对于所选的extent(以地图单位为单位)和要缓存的每个zoom级别,执行以下操作:

For (3), you'll probably want to limit downloading to a small extent. Then, for the chosen extent (in map units) and each zoom level you want to cache, do something like this:

const tilegrid = source.getTileGrid();
const projection = map.getView().getProjection();
const getUrl = source.getTileUrlFunction();
tilegrid.forEachTileCoord(extent, zoom, tilecoord => {
  const url = getUrl(tilecoord, devicePixelRatio, projection);
  fetch(url).then(response => {
    if (response.ok) {
      response.blob().then(blob => {
        const tx = db.transaction('tiles', 'readwrite');
        const tiles = tx.objectStore('tiles');
        tiles.put(url, blob);
      });
    }
  });
});

这篇关于如何使用“开放层"下载,存储和加载图块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆