Animate Marker
Runnable MapLibre GL JS example: Animate Marker. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:标记沿路线移动
核心逻辑:预先把路线重采样成等距点,rAF 里推进索引并 setLngLat
数据:页面内构造的配送路线与 200 个采样点
依赖: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:120px}
.bar button{background:#fff;border:1px solid #cfd6df;border-radius:4px;padding:3px 10px;
font:12px/1.4 inherit;color:#3a4250;cursor:pointer}
.bar button:hover{border-color:#2e86de;color:#2e86de}
#map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
<span>进度 <b id="p">0%</b></span>
<label>速度 <input id="s" type="range" min="0.2" max="3" step="0.1" value="1"> <b id="sv">1.0</b></label>
<button id="play">暂停</button>
<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 path = [
[116.20, 39.99], [117.10, 39.20], [117.60, 37.70],
[118.60, 35.50], [119.60, 33.20], [120.60, 31.60],
[121.47, 31.23], [119.80, 30.10], [117.20, 30.60],
[115.30, 32.90], [116.20, 39.99]
];
var map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [118, 35],
zoom: 5.6,
attributionControl: { compact: true, customAttribution: 'MapLibre demo tiles' }
});
map.addControl(new maplibregl.NavigationControl(), 'top-right');
/* 按线段长度分配采样点数,得到近似等距的点列 */
function resample(coords, total) {
var segs = [];
var sum = 0;
var i;
for (i = 0; i < coords.length - 1; i++) {
var a = coords[i];
var b = coords[i + 1];
var d = Math.sqrt(Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2));
segs.push(d);
sum += d;
}
var out = [];
var target = i = 0;
while (out.length < total && target <= sum) {
var walk = 0;
i = 0;
while (i < segs.length && walk + segs[i] < target) {
walk += segs[i];
i++;
}
if (i >= coords.length - 1) break;
var t = segs[i] === 0 ? 0 : (target - walk) / segs[i];
out.push([
coords[i][0] + (coords[i + 1][0] - coords[i][0]) * t,
coords[i][1] + (coords[i + 1][1] - coords[i][1]) * t
]);
target += sum / total;
}
return out;
}
var samples = resample(path, 200);
var pEl = document.getElementById('p');
var marker = new maplibregl.Marker({ color: '#e8590c', scale: 1.1 })
.setLngLat(samples[0])
.addTo(map);
var popup = new maplibregl.Popup({ offset: 20, closeButton: false })
.setHTML('配送中');
marker.setPopup(popup);
map.on('load', function () {
map.addSource('route', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: { type: 'LineString', coordinates: path }
}]
}
});
map.addLayer({
id: 'route',
type: 'line',
source: 'route',
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: { 'line-color': '#e8590c', 'line-width': 3, 'line-opacity': 0.55 }
});
map.addSource('start', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { n: '起点' }, geometry: { type: 'Point', coordinates: path[0] } },
{ type: 'Feature', properties: { n: '终点' }, geometry: { type: 'Point', coordinates: path[path.length - 1] } }
]
}
});
map.addLayer({
id: 'ends',
type: 'circle',
source: 'start',
paint: {
'circle-radius': 6,
'circle-color': '#2e86de',
'circle-stroke-width': 2,
'circle-stroke-color': '#ffffff'
}
});
});
var idx = 0;
var speed = 1;
var running = true;
function tick() {
if (running) {
idx += 0.6 * speed;
if (idx >= samples.length) idx = 0;
var at = samples[Math.floor(idx)];
marker.setLngLat(at);
pEl.textContent = Math.round(idx / samples.length * 100) + '%';
}
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
document.getElementById('s').addEventListener('input', function () {
speed = parseFloat(this.value);
document.getElementById('sv').textContent = speed.toFixed(1);
});
document.getElementById('play').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.