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

Polygon Layer

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

Source

demos/maplibre-polygon-layer.html
<!--
  示例:面图层
  核心逻辑:面图层按属性分段着色,promoteId 配合 setFeatureState 做悬停高亮
  依赖: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:12px;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}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <span>悬停 <b id="hover">—</b></span>
  <span>点击网格可查看数值</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 features = [];
  var id = 0;
  for (var row = 0; row < 4; row++) {
    for (var col = 0; col < 5; col++) {
      var x0 = 100 + col * 2.4;
      var y0 = 28 + row * 2.4;
      features.push({
        type: 'Feature',
        id: id,
        properties: {
          id: id,
          value: 15 + Math.round(Math.random() * 75)
        },
        geometry: {
          type: 'Polygon',
          coordinates: [[
            [x0, y0], [x0 + 2.2, y0], [x0 + 2.2, y0 + 2.2], [x0, y0 + 2.2], [x0, y0]
          ]]
        }
      });
      id++;
    }
  }

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

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

  map.on('load', function () {
    map.addSource('grid', {
      type: 'geojson',
      data: { type: 'FeatureCollection', features: features },
      promoteId: 'id'
    });

    map.addLayer({
      id: 'grid-fill',
      type: 'fill',
      source: 'grid',
      paint: {
        'fill-color': [
          'step', ['get', 'value'],
          '#e8f0f8',
          30, '#b9d4ec',
          55, '#7fb0d9',
          75, '#4a87bf',
          '#1f5fd0'
        ],
        'fill-opacity': [
          'case',
          ['boolean', ['feature-state', 'hover'], false],
          0.92,
          0.58
        ]
      }
    });

    map.addLayer({
      id: 'grid-line',
      type: 'line',
      source: 'grid',
      paint: {
        'line-color': '#2f5f8a',
        'line-width': 0.8,
        'line-opacity': 0.7
      }
    });

    var hovered = null;

    map.on('mousemove', 'grid-fill', function (e) {
      if (!e.features.length) return;
      var f = e.features[0];

      if (hovered !== null && hovered !== f.id) {
        map.setFeatureState({ source: 'grid', id: hovered }, { hover: false });
      }
      hovered = f.id;
      map.setFeatureState({ source: 'grid', id: hovered }, { hover: true });

      document.getElementById('hover').textContent =
        '网格 ' + f.id + ' · 数值 ' + f.properties.value;
      map.getCanvas().style.cursor = 'pointer';
    });

    map.on('mouseleave', 'grid-fill', function () {
      if (hovered !== null) {
        map.setFeatureState({ source: 'grid', id: hovered }, { hover: false });
      }
      hovered = null;
      document.getElementById('hover').textContent = '—';
      map.getCanvas().style.cursor = '';
    });
  });

  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 · EXAMPLEPolygon Pattern MapLibre GL JS · EXAMPLEPopup MapLibre GL JS · EXAMPLEPopup Card