Atlaslog
Atlaslog / Examples / Leaflet / WMS
Leaflet · Runnable Example

WMS

Runnable Leaflet example: WMS. 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-wms.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/leaflet-wms.html
<!--
  示例:WMS 图层
  要点:L.tileLayer.wms 参数(layers / format / transparent / version)、setParams 切换、请求失败降级为本地模拟瓦片
  依赖: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>WMS 图层</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 .sep{width:1px;height:16px;background:#dfe3e9}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <button id="opacity">透明度 0.55</button>
  <button id="version">切换到 1.1.1</button>
  <button id="format">切换到 JPEG</button>
  <span class="sep"></span>
  <span id="info">WMS 1.3.0 · image/png · transparent=true</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: 11, zoomSnap: 0.5 });

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

  var info = document.getElementById('info');
  var active = null;
  var useWms = true;

  var wms = L.tileLayer.wms('https://ows.terrestris.de/osm/service?', {
    layers: 'OSM-WMS',
    styles: '',
    format: 'image/png',
    transparent: true,
    version: '1.3.0',
    opacity: 0.55,
    attribution: 'WMS &copy; terrestris'
  }).addTo(map);

  active = wms;

  /* 请求真实服务;连续失败时退回本地生成的模拟瓦片,页面照常可用 */
  var fails = 0;
  wms.on('tileerror', function () {
    if (++fails !== 3 || !useWms) return;
    useWms = false;
    map.removeLayer(wms);
    active = mockWms().addTo(map);
    info.textContent = 'WMS 服务不可达,已切换为本地模拟瓦片';
  });

  /* 确定性伪随机,保证同一块瓦片重绘结果一致 */
  function seeded(coords) {
    var s = Math.abs(coords.x * 73856093 ^ coords.y * 19349663 ^ coords.z * 83492791) % 2147483647;
    return function () {
      s = (s * 16807) % 2147483647;
      return (s - 1) / 2147483646;
    };
  }

  var MockWms = L.GridLayer.extend({
    createTile: function (coords) {
      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 rand = seeded(coords);

      ctx.fillStyle = 'rgba(31, 95, 208, 0.10)';
      ctx.fillRect(0, 0, size.x, size.y);

      for (var i = 0; i < 7; i++) {
        var cx = rand() * size.x;
        var cy = rand() * size.y;
        var r = 21 + rand() * 46;
        var g = ctx.createRadialGradient(cx, cy, 2, cx, cy, r);
        g.addColorStop(0, 'rgba(37, 99, 235, 0.55)');
        g.addColorStop(1, 'rgba(37, 99, 235, 0)');
        ctx.fillStyle = g;
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, Math.PI * 2);
        ctx.fill();
      }

      ctx.fillStyle = 'rgba(88, 96, 110, 0.8)';
      ctx.font = '11px sans-serif';
      ctx.fillText('OSM-WMS · 本地模拟', 8, size.y - 10);

      return tile;
    }
  });

  function mockWms() {
    return new MockWms({ opacity: 0.55, attribution: '本地模拟数据' });
  }

  var dim = 0.55;
  document.getElementById('opacity').addEventListener('click', function () {
    dim = dim > 0.6 ? 0.35 : 0.75;
    active.setOpacity(dim);
    this.textContent = '透明度 ' + dim;
  });

  var v111 = false;
  document.getElementById('version').addEventListener('click', function () {
    if (!useWms) return;
    v111 = !v111;
    wms.setParams({ version: v111 ? '1.1.1' : '1.3.0' });
    this.textContent = v111 ? '切换到 1.3.0' : '切换到 1.1.1';
    info.textContent = 'WMS ' + (v111 ? '1.1.1' : '1.3.0') + ' · image/png · transparent=true';
  });

  var jpeg = false;
  document.getElementById('format').addEventListener('click', function () {
    if (!useWms) return;
    jpeg = !jpeg;
    wms.setParams({
      format: jpeg ? 'image/jpeg' : 'image/png',
      transparent: !jpeg
    });
    this.textContent = jpeg ? '切换到 PNG' : '切换到 JPEG';
    info.textContent = 'WMS 1.3.0 · ' + (jpeg ? 'image/jpeg · 不透明' : 'image/png · transparent=true');
  });

  map.on('moveend', function () {
    if (!useWms) return;
    var c = map.getCenter();
    console.log('GetMap 请求参数', {
      layers: wms.wmsParams.layers,
      version: wms.wmsParams.version,
      format: wms.wmsParams.format,
      transparent: wms.wmsParams.transparent,
      center: [c.lat.toFixed(4), c.lng.toFixed(4)]
    });
  });
})();
</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 · EXAMPLEZoom Slider Leaflet · EXAMPLEBasemap Switch Leaflet · EXAMPLEMinimal Scene