Atlaslog
Atlaslog / Examples / MapLibre GL JS / Layer Color Buttons
MapLibre GL JS · Runnable Example

Layer Color Buttons

Runnable MapLibre GL JS example: Layer Color Buttons. 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-color-buttons.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-layer-color-buttons.html
<!--
  示例:按钮改图层颜色
  核心逻辑:setPaintProperty 改 fill-color,并带上 300ms 的过渡时长
  数据:页面内构造的四个片区多边形
  依赖:MapLibre GL JS 4 · jsDelivr CDN · demotiles 样式
-->
<!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:8px;align-items:center;padding:8px 12px;
       background:#f6f7f9;border-bottom:1px solid #e3e6ea;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar b{color:#16181d;font-weight:600}
  .bar button{background:#fff;border:1px solid #cfd6df;border-radius:16px;padding:3px 12px;
       font:12px/1.4 inherit;color:#3a4250;cursor:pointer}
  .bar button:hover{border-color:#2e86de;color:#2e86de}
  .bar input[type=range]{width:110px}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <span>填充色</span>
  <button data-color="#4dabf7">蓝</button>
  <button data-color="#51cf66">绿</button>
  <button data-color="#ffa94d">橙</button>
  <button data-color="#e599f7">紫</button>
  <label>不透明度 <input id="o" type="range" min="0.1" max="0.9" step="0.05" value="0.45"> <b id="ov">0.45</b></label>
  <span>切换时走 300ms 过渡</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;
  }

  function block(lng, lat, w, h) {
    return [[
      [lng - w, lat - h], [lng + w, lat - h],
      [lng + w, lat + h], [lng - w, lat + h],
      [lng - w, lat - h]
    ]];
  }

  var zones = [
    { name: '华北', c: [116, 39, 5, 3.2] },
    { name: '华东', c: [119.5, 31.5, 5, 3] },
    { name: '华南', c: [113, 24, 4.4, 2.6] },
    { name: '西部', c: [102, 33, 7, 4] }
  ];

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

  map.addControl(new maplibregl.NavigationControl(), 'top-right');

  var oEl = document.getElementById('o');
  var ovEl = document.getElementById('ov');

  map.on('load', function () {
    map.addSource('zones', {
      type: 'geojson',
      data: {
        type: 'FeatureCollection',
        features: zones.map(function (z) {
          return {
            type: 'Feature',
            properties: { name: z.name },
            geometry: { type: 'Polygon', coordinates: block.apply(null, z.c) }
          };
        })
      }
    });

    map.addLayer({
      id: 'zones-fill',
      type: 'fill',
      source: 'zones',
      paint: {
        'fill-color': '#4dabf7',
        'fill-opacity': 0.45,
        /* 颜色与透明度变化都在这段时长里插值 */
        'fill-color-transition': { duration: 300, delay: 0 },
        'fill-opacity-transition': { duration: 300, delay: 0 }
      }
    });

    map.addLayer({
      id: 'zones-line',
      type: 'line',
      source: 'zones',
      paint: { 'line-color': '#2b4a6f', 'line-width': 1.2 }
    });
  });

  Array.prototype.forEach.call(document.querySelectorAll('button[data-color]'), function (btn) {
    btn.addEventListener('click', function () {
      if (!map.getLayer('zones-fill')) return;
      map.setPaintProperty('zones-fill', 'fill-color', btn.getAttribute('data-color'));
    });
  });

  oEl.addEventListener('input', function () {
    var v = parseFloat(this.value);
    ovEl.textContent = v.toFixed(2);
    if (map.getLayer('zones-fill')) {
      map.setPaintProperty('zones-fill', 'fill-opacity', v);
    }
  });

  map.on('mousemove', 'zones-fill', function (e) {
    map.getCanvas().style.cursor = 'pointer';
    map.getCanvas().title = e.features[0].properties.name;
  });

  map.on('mouseleave', 'zones-fill', function () {
    map.getCanvas().style.cursor = '';
    map.getCanvas().title = '';
  });

  map.on('error', function (e) {
    if (e.error) console.warn('地图错误:' + e.error.message);
  });
})();
</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 Switch MapLibre GL JS · EXAMPLELayer Visibility MapLibre GL JS · EXAMPLELine Gradient