代码
const map = new BMap.Map('map', {
displayOptions: {
poi: false,
},
});
map.centerAndZoom(new BMap.Point(116.39, 39.99), 14);
map.enableScrollWheelZoom(true);
// 轨迹坐标 [经度, 纬度]
const coords = [
[116.310823, 40.003418],
[116.311538, 39.994606],
[116.312181, 39.991014],
[116.334538, 39.991369],
[116.360841, 39.991777],
[116.387144, 39.992185],
[116.413447, 39.992593],
[116.43975, 39.99299],
[116.468679, 39.993441],
[116.468894, 39.985586],
[116.469144, 39.97616],
[116.469394, 39.966734],
[116.469679, 39.955737],
];
// 创建轨迹动画图层
const trackLine = new BMap.TrackLine({
// strokeColor: 'rgba(25, 25, 250, 1)',
strokeWeight: 10,
passedColor: 'rgba(153, 153, 153, 1)',
duration: 10,
// 沿线箭头纹理:间隔平铺,提示行驶方向
strokeTextureUrl: 'https://mapopen-pub-jsapi.bj.bcebos.com/jsapiGlgeo/img/down.png',
strokeTextureWidth: 64,
strokeTextureHeight: 32,
strokeTextureSpaced: true,
strokeTextureGap: 32,
// 车辆图标
movePoint: {
type: 'ground',
url: 'https://jsapi-demo.bj.bcebos.com/images/markers/car.png',
size: [22, 44],
adjustSize: true,
},
});
// 以 GeoJSON LineString 设置数据,并添加到地图
trackLine.setData({
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: coords,
},
});
map.addLayer(trackLine);
// 播放控制:暂停后再点「开始播放」从暂停处继续,否则从头播放
let paused = false;
document.getElementById('btn-start').onclick = function () {
if (paused) {
trackLine.resume();
paused = false;
} else {
trackLine.start();
}
};
document.getElementById('btn-pause').onclick = function () {
trackLine.pause();
paused = true;
};
// 重置:停止播放并回到起点,同时倍速也会恢复为 1,之后点「开始播放」从头开始
document.getElementById('btn-reset').onclick = function () {
trackLine.stop();
paused = false;
document.getElementById('speed-text').innerText = '当前:' + trackLine.getSpeed() + ' 倍速';
};
// 调整速度:setSpeed(n) 是「设为 n 倍速」,播放过程中可随时切换
function changeSpeed(speed) {
trackLine.setSpeed(speed);
document.getElementById('speed-text').innerText = '当前:' + trackLine.getSpeed() + ' 倍速';
}
document.getElementById('btn-speed-05').onclick = function () {
changeSpeed(0.5);
};
document.getElementById('btn-speed-1').onclick = function () {
changeSpeed(1);
};
document.getElementById('btn-speed-2').onclick = function () {
changeSpeed(2);
};
预览