代码
import {
  BaiduMapConfig,
  BaiduVectorTileProvider,
  Engine,
  GeoJSONDataSource,
  Label,
  Polyline,
  Twin,
  twinConstants,
} from '@baidumap/mapv-three';

const container = document.querySelector('#map');
const info = document.querySelector('.info');
const operate = document.querySelector('.operate');
const center = [116.40291182145938, 39.93219301296199];
// 示例中心会注入 AK,复制代码时可填写自己的密钥。
const ak = BaiduMapConfig.ak || '您的密钥';
const hasKey = Boolean(ak.trim()) && !ak.includes('密钥');
const provider = hasKey
  ? new BaiduVectorTileProvider({
      ak,
      displayOptions: {
        flat: true,
        building: false,
        poi: false,
      },
    })
  : null;
const engine = new Engine(container, {
  map: {
    projection: 'ecef',
    provider,
    center,
    range: (1140 * 1.14) / Math.min(1.14, container.clientWidth / container.clientHeight),
    pitch: 41,
    heading: 0,
  },
  clock: {
    currentTime: new Date('2026-06-21T02:30:00Z'),
  },
  rendering: {
    enableAnimationLoop: true,
  },
});
// 景山公园四周的道路中心线,BD-09 经纬度。
const route = [
  [116.40015134574526, 39.92951160949869],
  [116.40598864622852, 39.929742549328346],
  [116.40578391075242, 39.93450881154934],
  [116.40575840566817, 39.93462353952018],
  [116.40567540642792, 39.93472412524997],
  [116.4055403440982, 39.9347780080741],
  [116.40531986913238, 39.93480222421779],
  [116.40041471323646, 39.93473490926688],
  [116.40018080007968, 39.93470454480644],
  [116.40000781997928, 39.934602613473345],
  [116.39994313508183, 39.93445167534396],
  [116.40015134574526, 39.92951160949869],
];

// 离线预览显示车辆的实际路线。百度底图接通时直接使用底图道路。
if (!provider) {
  const line = engine.add(
    new Polyline({
      color: '#387f87',
      width: 4,
      vertexHeights: true,
    }),
  );
  line.dataSource = GeoJSONDataSource.fromGeoJSON([
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: route.map(([lng, lat]) => [lng, lat, 0.1]),
      },
    },
  ]);
}

// 车型编号 3 对应轿车,6 对应公交车,均使用随 SDK 提供的写实模型。
const models = twinConstants.REALISTIC_TEMPLATE_MODEL;
const modelConfig = {
  3: models.CAR,
  6: models.BUS,
};
const vehicleLabel = new Label({
  type: 'text',
  textSize: 13,
  textFillStyle: '#ffe08a',
  textStrokeStyle: '#263d3b',
  textStrokeWidth: 3,
  pixelOffset: [0, 34],
  depthTest: false,
  transparent: true,
});
const twin = engine.add(
  new Twin({
    delay: 1000,
    modelConfig,
    keepSize: true,
    maxScale: 6,
    objects: [vehicleLabel],
    objectAttributes: {
      text: 'focusLabel',
    },
  }),
);
// 车源使用真北顺时针角度,Twin 使用正东方向起算的弧度。
twin.dataProvider
  .process('id', 'vehicleId')
  .process('time', 'timestamp')
  .process('point', (item) => [item.longitude, item.latitude, item.altitude])
  .process('dir', (item) => ((90 - item.heading) * Math.PI) / 180)
  // 显示比例只影响车身大小,车辆轨迹保持实际经纬度。
  .process('scale', (item) => {
    const size = item.category === 'bus' ? 2.5 : 3.1;
    return [size, size, size];
  })
  .process('modelType', (item) => (item.category === 'bus' ? 6 : 3))
  .process('focusLabel', (item) => (item.vehicleId === 'V-01' ? item.vehicleId : ''));

// 回放源和真实服务使用同一种消息结构,每条消息是一帧完整车辆快照。
// 小范围内用局部米制换算计算路径距离和航向。
const metersPerLongitude = 111320 * Math.cos((center[1] * Math.PI) / 180);
const metersPerLatitude = 111100;
const segments = route.slice(1).map(([lng, lat], index) => {
  const [startLng, startLat] = route[index];
  const deltaLng = lng - startLng;
  const deltaLat = lat - startLat;
  const east = deltaLng * metersPerLongitude;
  const north = deltaLat * metersPerLatitude;
  return {
    startLng,
    startLat,
    deltaLng,
    deltaLat,
    length: Math.hypot(east, north),
    heading: (90 - (Math.atan2(north, east) * 180) / Math.PI + 360) % 360,
  };
});
const routeLength = segments.reduce((total, segment) => total + segment.length, 0);
function sampleRoute(distance) {
  let remaining = distance % routeLength;
  for (const segment of segments) {
    if (remaining < segment.length) {
      const ratio = remaining / segment.length;
      return {
        longitude: segment.startLng + segment.deltaLng * ratio,
        latitude: segment.startLat + segment.deltaLat * ratio,
        altitude: 0.45,
        heading: segment.heading,
      };
    }
    remaining -= segment.length;
  }
}

const startedAt = Date.now();
function makeFrame() {
  const timestamp = Date.now();
  const traveled = 195 + (timestamp - startedAt) * 0.011;
  return {
    timestamp,
    vehicles: Array.from({length: 8}, (_, index) => ({
      vehicleId: `V-0${index + 1}`,
      ...sampleRoute(traveled + (index * routeLength) / 8),
      category: index % 3 === 0 ? 'bus' : 'car',
      speedKmh: 40,
      color: index % 3 === 0 ? '#e5a03a' : '#438bed',
    })),
  };
}
const toggle = operate.querySelector('#vehicle-type');
let category = 'bus';
toggle.onclick = () => {
  category = category === 'bus' ? 'car' : 'bus';
  toggle.textContent = category === 'bus' ? '将 V-01 切换为轿车' : '将 V-01 切换为公交车';
  showType();
};
function showType() {
  info.textContent = `V-01 · ${category === 'bus' ? '公交车' : '轿车'}(车型 ${category === 'bus' ? 6 : 3})`;
}
function pushFrame() {
  const {timestamp, vehicles} = makeFrame();
  vehicles[0].category = category;
  twin.push(
    vehicles.map((item) => ({
      ...item,
      timestamp,
    })),
  );
}
showType();
pushFrame();
const frameTimer = setInterval(pushFrame, 250);

window.addEventListener('pagehide', ({persisted}) => {
  if (!persisted) {
    clearInterval(frameTimer);
    engine.dispose();
  }
});

通过 Twin 映射编号、BD-09 经纬度、朝向和车型字段,在景山公园道路回放中切换 V-01 的写实轿车和公交车模型。

预览