Atlaslog
Atlaslog / Examples / MapLibre GL JS / Layer Switch
MapLibre GL JS · Runnable Example

Layer Switch

Runnable MapLibre GL JS example: Layer Switch. 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 MapLibre GL JS examples
/demos/maplibre-layer-switch.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-layer-switch.html
<!--
  示例:图层切换
  核心逻辑:三条线路各占一个图层,复选框用 setLayoutProperty 控制可见性
  依赖:MapLibre GL JS 4 · jsDelivr CDN · demotiles 免 Key 样式
-->
<!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/maplibre-gl@4/dist/maplibre-gl.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;color:#16181d}
  .bar{flex:0 0 auto;display:flex;gap:16px;align-items:center;padding:8px 12px;
       background:#f6f7f9;border-bottom:1px solid #e3e6ea;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  .bar i{display:inline-block;width:14px;height:3px;border-radius:2px}
  .bar b{color:#16181d;font-weight:600}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <label><input type="checkbox" data-layer="jingguang" checked><i style="background:#1f5fd0"></i> 京广线</label>
  <label><input type="checkbox" data-layer="jinghu" checked><i style="background:#c2410c"></i> 京沪线</label>
  <label><input type="checkbox" data-layer="longhai" checked><i style="background:#17694a"></i> 陇海线</label>
  <span>可见 <b id="n">3</b> / 3</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js"></script>
<script>
(function () {
  'use strict';

  if (typeof maplibregl === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#b42318">MapLibre 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var lines = {
    jingguang: {
      color: '#1f5fd0',
      coords: [[116.391, 39.907], [114.514, 38.042], [113.625, 34.746],
               [114.305, 30.593], [112.938, 28.228], [113.264, 23.129]]
    },
    jinghu: {
      color: '#c2410c',
      coords: [[116.391, 39.907], [117.200, 39.133], [117.000, 36.651],
               [118.797, 32.060], [121.474, 31.230]]
    },
    longhai: {
      color: '#17694a',
      coords: [[119.221, 34.596], [117.184, 34.261], [113.625, 34.746],
               [108.940, 34.341], [103.834, 36.061]]
    }
  };

  var map = new maplibregl.Map({
    container: 'map',
    style: 'https://demotiles.maplibre.org/style.json',
    center: [112, 33],
    zoom: 3,
    attributionControl: {
      compact: true,
      customAttribution: 'MapLibre demo tiles'
    }
  });

  map.on('load', function () {
    Object.keys(lines).forEach(function (id) {
      map.addSource(id, {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: { name: id },
          geometry: { type: 'LineString', coordinates: lines[id].coords }
        }
      });

      map.addLayer({
        id: id,
        type: 'line',
        source: id,
        layout: { 'line-cap': 'round', 'line-join': 'round' },
        paint: {
          'line-color': lines[id].color,
          'line-width': ['interpolate', ['linear'], ['zoom'], 2, 1.8, 6, 4]
        }
      });
    });

    refresh();
  });

  function refresh() {
    var checked = document.querySelectorAll('.bar input[type=checkbox]:checked').length;
    document.getElementById('n').textContent = checked;
  }

  document.querySelectorAll('.bar input[type=checkbox]').forEach(function (box) {
    box.addEventListener('change', function () {
      var id = this.getAttribute('data-layer');
      if (!map.getLayer(id)) return;

      map.setLayoutProperty(id, 'visibility', this.checked ? 'visible' : 'none');
      refresh();
    });
  });

  map.addControl(new maplibregl.NavigationControl(), 'top-right');
})();
</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 MapLibre GL JS examples

MapLibre GL JS · EXAMPLELayer Visibility MapLibre GL JS · EXAMPLELine Gradient MapLibre GL JS · EXAMPLELine Layer