Atlaslog
Atlaslog / Examples / MapLibre GL JS / Path Animation
MapLibre GL JS · Runnable Example

Path Animation

Runnable MapLibre GL JS example: Path Animation. 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-path-animation.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-path-animation.html
<!--
  示例:路径动画
  核心逻辑:预计算折线上等距采样点,requestAnimationFrame 里更新已走轨迹与头部点
  依赖: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}
  .btn{border:1px solid #cdd3db;background:#fff;border-radius:4px;padding:3px 9px;
       font:12px/1.5 inherit;color:#16181d;cursor:pointer}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <button class="btn" id="toggle">暂停</button>
  <span>进度 <b id="pct">0%</b></span>
  <span>轨迹 <b id="km">0.0 km</b></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 ROUTE = [
    [116.41, 39.90], [117.20, 36.65], [118.78, 32.06],
    [121.47, 31.23], [120.15, 30.28], [118.80, 32.06],
    [114.31, 30.59], [112.98, 28.19], [113.26, 23.13]
  ];

  /* 按经纬度距离累计,插值出 600 个等距点 */
  function segLen(a, b) {
    var dx = (b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math.PI / 180);
    var dy = b[1] - a[1];
    return Math.sqrt(dx * dx + dy * dy);
  }

  var cum = [0];
  for (var i = 1; i < ROUTE.length; i++) {
    cum.push(cum[i - 1] + segLen(ROUTE[i - 1], ROUTE[i]));
  }
  var total = cum[cum.length - 1];
  var STEPS = 600;
  var path = [];
  for (var s = 0; s <= STEPS; s++) {
    var target = total * s / STEPS;
    var k = 1;
    while (k < cum.length - 1 && cum[k] < target) k++;
    var t = (target - cum[k - 1]) / (cum[k] - cum[k - 1] || 1);
    path.push([
      ROUTE[k - 1][0] + (ROUTE[k][0] - ROUTE[k - 1][0]) * t,
      ROUTE[k - 1][1] + (ROUTE[k][1] - ROUTE[k - 1][1]) * t
    ]);
  }

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

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

  var idx = 0;
  var running = true;
  var last = 0;

  function lineData(n) {
    return {
      type: 'Feature',
      properties: {},
      geometry: { type: 'LineString', coordinates: path.slice(0, Math.max(2, n)) }
    };
  }

  function headData(n) {
    return {
      type: 'Feature',
      properties: {},
      geometry: { type: 'Point', coordinates: path[Math.min(n, path.length - 1)] }
    };
  }

  map.on('load', function () {
    map.addSource('full-route', {
      type: 'geojson',
      data: { type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: ROUTE } }
    });

    map.addSource('trail', { type: 'geojson', data: lineData(1) });
    map.addSource('head', { type: 'geojson', data: headData(0) });

    map.addLayer({
      id: 'full-route',
      type: 'line',
      source: 'full-route',
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': '#9fb4c7',
        'line-width': 2,
        'line-dasharray': [2, 2],
        'line-opacity': 0.9
      }
    });

    map.addLayer({
      id: 'trail',
      type: 'line',
      source: 'trail',
      layout: { 'line-cap': 'round', 'line-join': 'round' },
      paint: {
        'line-color': '#e8590c',
        'line-width': 4
      }
    });

    map.addLayer({
      id: 'head-halo',
      type: 'circle',
      source: 'head',
      paint: {
        'circle-radius': 12,
        'circle-color': '#e8590c',
        'circle-opacity': 0.22
      }
    });

    map.addLayer({
      id: 'head',
      type: 'circle',
      source: 'head',
      paint: {
        'circle-radius': 5,
        'circle-color': '#ffffff',
        'circle-stroke-color': '#e8590c',
        'circle-stroke-width': 2.5
      }
    });

    requestAnimationFrame(step);
  });

  function step(ts) {
    if (running && ts - last > 16) {
      last = ts;
      idx += 1;
      if (idx > STEPS) idx = 0;

      map.getSource('trail').setData(lineData(idx + 1));
      map.getSource('head').setData(headData(idx));

      document.getElementById('pct').textContent =
        Math.round(idx / STEPS * 100) + '%';
      document.getElementById('km').textContent =
        (total * 111 * idx / STEPS).toFixed(1) + ' km';
    }
    requestAnimationFrame(step);
  }

  document.getElementById('toggle').addEventListener('click', function () {
    running = !running;
    this.textContent = running ? '暂停' : '继续';
  });

  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 · EXAMPLEPerformance MapLibre GL JS · EXAMPLEPitch Bearing MapLibre GL JS · EXAMPLEPolygon Layer