代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Polyline,
} from '@baidumap/mapv-three';
BaiduMapConfig.ak = '您的密钥';
const container = document.getElementById('map');
const aspect = container.clientWidth / container.clientHeight;
const engine = new Engine(container, {
map: {
center: [116.3961, 39.9012],
range: (2_750 * 1.4) / Math.min(1.4, aspect),
pitch: 0,
provider: new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
}),
},
rendering: {
enableAnimationLoop: true,
},
});
// 路径来自百度驾车规划结果,坐标为 BD-09。
const routes = [
{
// 珠市口西大街至南新华街
color: '#c04f30',
path: [
[116.400445, 39.896646],
[116.399088, 39.896407],
[116.395619, 39.896018],
[116.393357, 39.895884],
[116.393277, 39.895983],
[116.392909, 39.896019],
[116.391803, 39.896015],
[116.391226, 39.895958],
[116.391183, 39.899716],
[116.391062, 39.901524],
[116.390911, 39.902821],
[116.39082, 39.90426],
],
},
{
// 煤市街
color: '#176abe',
path: [
[116.400947, 39.904046],
[116.400828, 39.903615],
[116.400818, 39.903355],
[116.401099, 39.902087],
[116.401119, 39.901768],
[116.401001, 39.900347],
[116.400962, 39.899427],
[116.401052, 39.898888],
[116.401353, 39.89794],
],
},
{
// 前门西大街
color: '#6835b8',
path: [
[116.391087, 39.906303],
[116.398211, 39.906598],
],
},
];
const dataSource = GeoJSONDataSource.fromGeoJSON(
routes.map(({color, path}) => ({
type: 'Feature',
geometry: {
type: 'LineString',
// 在底图上方抬升 12 米,避免路线和路面共面。
coordinates: path.map(([lng, lat]) => [lng, lat, 12]),
},
properties: {color},
})),
);
dataSource.defineAttribute('color');
const trail = engine.add(
new Polyline({
vertexColors: true,
lineWidth: 8,
keepSize: true,
transparent: true,
enableAnimation: true,
animationTailType: 1,
animationTailRatio: 0.45,
animationSpeed: 0.22,
animationIdle: 0,
}),
);
trail.dataSource = dataSource;
const toggle = document.getElementById('flow');
toggle.addEventListener('click', () => {
trail.enableAnimation = !trail.enableAnimation;
toggle.setAttribute('aria-pressed', String(trail.enableAnimation));
toggle.textContent = trail.enableAnimation ? '暂停流动' : '播放流动';
engine.requestRender();
});
在珠市口西大街至南新华街、煤市街和前门西大街绘制三条不同颜色的路线。用一个 Polyline 按路线读取颜色并播放拖尾动画。暂停后显示完整路线。
预览