Atlaslog
Atlaslog / Examples / MapLibre GL JS / Line Gradient
MapLibre GL JS · Runnable Example

Line Gradient

Runnable MapLibre GL JS example: Line Gradient. 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-line-gradient.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-line-gradient.html
<!--
  示例:线渐变色
  核心逻辑:geojson 源开启 lineMetrics,line-gradient 用 line-progress 做颜色插值
  数据:页面内构造的三条货运线路,按沿线进程着色
  依赖: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:14px;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 input[type=range]{width:130px}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <span>线路 <b>3</b></span>
  <label>线宽 <input id="w" type="range" min="2" max="14" step="1" value="6"> <b id="wv">6</b></label>
  <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 routes = [
    {
      name: '京沪线',
      coords: [[116.39, 39.90], [117.20, 39.13], [117.00, 36.65], [118.80, 32.06], [121.47, 31.23]]
    },
    {
      name: '京广线',
      coords: [[116.39, 39.90], [114.51, 38.04], [114.30, 30.59], [113.00, 28.20], [113.26, 23.12]]
    },
    {
      name: '沪昆线',
      coords: [[121.47, 31.23], [120.15, 30.28], [117.28, 31.86], [114.30, 30.59], [106.55, 29.56], [102.71, 25.04]]
    }
  ];

  var geojson = {
    type: 'FeatureCollection',
    features: routes.map(function (r) {
      return {
        type: 'Feature',
        properties: { name: r.name },
        geometry: { type: 'LineString', coordinates: r.coords }
      };
    })
  };

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

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

  map.on('load', function () {
    /* lineMetrics 必须开,否则 line-progress 取不到值 */
    map.addSource('routes', {
      type: 'geojson',
      data: geojson,
      lineMetrics: true
    });

    map.addLayer({
      id: 'routes',
      type: 'line',
      source: 'routes',
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-width': 6,
        'line-gradient': [
          'interpolate', ['linear'], ['line-progress'],
          0, '#2e86de',
          0.35, '#37b24d',
          0.7, '#f59f00',
          1, '#f03e3e'
        ]
      }
    });
  });

  document.getElementById('w').addEventListener('input', function () {
    var v = parseInt(this.value, 10);
    document.getElementById('wv').textContent = v;
    if (map.getLayer('routes')) {
      map.setPaintProperty('routes', 'line-width', v);
    }
  });

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

  map.on('mouseleave', 'routes', 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 · EXAMPLELine Layer MapLibre GL JS · EXAMPLELive Update MapLibre GL JS · EXAMPLEMap Export