标记动画
通过每帧更新位置来制作标记动画;
<!DOCTYPE html>
<html lang="en">
<head>
<title>标记动画</title>
<meta property="og:description" content="通过每帧更新位置来制作标记动画" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// 莫斯科市中心的坐标
const center = [37.618423, 55.751244];
// 创建地图对象
const map = new maplibregl.Map({
container: 'map',
style:
'https://demotiles.maplibre.org/styles/osm-bright-gl-style/style.json',
center: center,
zoom: 16
});
// 等待地图加载完成
map.on('load', () => {
// 创建一个DOM元素用于标记
const el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(https://maplibre.org/maplibre-gl-js/docs/assets/pin.png)';
el.style.width = '41px';
el.style.height = '41px';
el.style.backgroundSize = '100%';
// 创建标记实例
const marker = new maplibregl.Marker(el)
.setLngLat(center)
.addTo(map);
// 圆周运动参数
const radius = 0.001; // 圆的半径(经度/纬度单位)
const duration = 10; // 一圈的秒数
let startTime;
function animateMarker(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = ((timestamp - startTime) / 1000) % duration; // 经过的秒数
const phase = (elapsed / duration) * (Math.PI * 2); // 转换为角度 (0-2π)
// 计算新的坐标位置(简单圆周运动)
const lng = center[0] + radius * Math.cos(phase);
const lat = center[1] + radius * Math.sin(phase);
// 更新标记位置
marker.setLngLat([lng, lat]);
// 请求下一个动画帧
requestAnimationFrame(animateMarker);
}
// 开始动画
requestAnimationFrame(animateMarker);
});
</script>
</body>
</html>