Atlaslog
Atlaslog / Examples / Leaflet / Tile Cache
Leaflet · Runnable Example

Tile Cache

Runnable Leaflet example: Tile Cache. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All Leaflet examples
/demos/leaflet-tile-cache.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/leaflet-tile-cache.html
<!--
  示例:瓦片缓存
  要点:重写 TileLayer.createTile 复用已下载 Image、命中率统计、清理缓存后重绘
  依赖:Leaflet 1.9.4 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>瓦片缓存</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:12px;color:#58606e}
  .bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:4px;cursor:pointer;
       border:1px solid #ccd1d9;background:#fff;color:#16181d}
  .bar button:hover{background:#eef0f3}
  .bar b{color:#16181d;font-weight:600;font-variant-numeric:tabular-nums}
  .bar .sep{width:1px;height:16px;background:#dfe3e9}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <button id="redraw">重绘瓦片</button>
  <button id="clear">清空缓存</button>
  <span class="sep"></span>
  <span>命中 <b id="hit">0</b> · 网络请求 <b id="miss">0</b></span>
  <span>缓存 <b id="size">0</b> 块</span>
  <span id="hint">拖到已看过的区域再回来,观察命中数变化</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
(function () {
  'use strict';

  var map = L.map('map', { center: [39.907359, 116.391263], zoom: 12, zoomSnap: 1 });

  var cache = new Map();
  var hit = 0;
  var miss = 0;

  var hitEl = document.getElementById('hit');
  var missEl = document.getElementById('miss');
  var sizeEl = document.getElementById('size');
  var hintEl = document.getElementById('hint');

  function refresh() {
    hitEl.textContent = hit;
    missEl.textContent = miss;
    sizeEl.textContent = cache.size;
    var total = hit + miss;
    if (total > 4) {
      hintEl.textContent = '命中率 ' + Math.round(hit / total * 100) + '%(共 ' + total + ' 次取瓦片)';
    }
  }

  /* 复用已经加载过的 Image,避免同一张瓦片重复走网络 */
  var CachedTiles = L.TileLayer.extend({
    createTile: function (coords, done) {
      var tile = L.DomUtil.create('canvas', 'leaflet-tile');
      var size = this.getTileSize();
      tile.width = size.x;
      tile.height = size.y;
      var ctx = tile.getContext('2d');
      var url = this.getTileUrl(coords);
      var cached = cache.get(url);

      if (cached) {
        hit++;
        ctx.drawImage(cached, 0, 0, size.x, size.y);
        setTimeout(function () { if (done) done(null, tile); }, 0);
        refresh();
        return tile;
      }

      miss++;
      var img = new Image();
      /* 只绘制不读像素,因此不必设 crossOrigin;要导出 canvas 时才需要 */

      img.onload = function () {
        cache.set(url, img);
        ctx.drawImage(img, 0, 0, size.x, size.y);
        if (done) done(null, tile);
        refresh();
      };

      img.onerror = function () {
        ctx.fillStyle = '#eef1f5';
        ctx.fillRect(0, 0, size.x, size.y);
        ctx.fillStyle = '#9aa3b0';
        ctx.font = '11px sans-serif';
        ctx.fillText('瓦片加载失败', 12, size.y / 2);
        if (done) done(new Error('tile error'), tile);
        refresh();
      };

      img.src = url;
      refresh();
      return tile;
    }
  });

  var layer = new CachedTiles('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
    maxZoom: 19,
    attribution: 'Tiles © Esri'
  }).addTo(map);

  layer.on('load', function () {
    /* 当前视野的瓦片全部就绪 */
  });

  document.getElementById('redraw').addEventListener('click', function () {
    /* 重绘会重新调用 createTile,已缓存的块应当全部命中 */
    layer.redraw();
  });

  document.getElementById('clear').addEventListener('click', function () {
    cache.clear();
    hit = 0;
    miss = 0;
    hintEl.textContent = '缓存已清空,重绘将重新发起网络请求';
    layer.redraw();
    refresh();
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More Leaflet examples

Leaflet · EXAMPLETile Filter Leaflet · EXAMPLETrack Playback Leaflet · EXAMPLEVideo Overlay