代码
const map = new BMap.Map('map');
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({
renderStage: 'poi',
// 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;
};
// 重置:停止播放并回到起点,之后点「开始播放」从头开始
document.getElementById('btn-reset').onclick = function () {
trackLine.stop();
paused = false;
};
// 调整样式:通过 setOptions 修改,播放进度会保留
// 渐变色:isLinear 为 true 时,线色按 linearTexture 色标沿轨迹渐变(覆盖 strokeColor)
function setLinear(stops) {
if (stops) {
trackLine.setOptions({isLinear: true, linearTexture: stops});
} else {
trackLine.setOptions({isLinear: false});
}
}
document.getElementById('btn-linear-1').onclick = function () {
setLinear([
[0, '#00c853'],
[0.5, '#ffd600'],
[1, '#d50000'],
]);
};
document.getElementById('btn-linear-2').onclick = function () {
setLinear([
[0, 'purple'],
[0.5, 'red'],
[1, 'green'],
]);
};
document.getElementById('btn-linear-0').onclick = function () {
setLinear(null);
};
// 已走过路段的颜色:传 'none' 则隐藏该段
function setPassedColor(color) {
trackLine.setOptions({passedColor: color});
}
document.getElementById('btn-passed-gray').onclick = function () {
setPassedColor('rgba(153, 153, 153, 1)');
};
document.getElementById('btn-passed-red').onclick = function () {
setPassedColor('rgba(230, 30, 30, 1)');
};
document.getElementById('btn-passed-none').onclick = function () {
setPassedColor('none');
};
// 线宽
function setWeight(weight) {
trackLine.setOptions({strokeWeight: weight});
}
document.getElementById('btn-weight-6').onclick = function () {
setWeight(6);
};
document.getElementById('btn-weight-10').onclick = function () {
setWeight(10);
};
document.getElementById('btn-weight-16').onclick = function () {
setWeight(16);
};
预览