代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
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,
},
})
: 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 twin = engine.add(
new Twin({
delay: 1000,
modelConfig,
keepSize: true,
maxScale: 6,
}),
);
// 车源使用真北顺时针角度,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));
const stream = operate.querySelector('#stream');
let socket = null;
let frameTimer = 0;
let latestTime = 0;
let addressError = false;
stream.oninput = () => {
addressError = false;
};
function stopFeed() {
clearInterval(frameTimer);
const previous = socket;
socket = null;
previous?.close();
latestTime = 0;
twin.reset();
}
function acceptFrame(frame, source) {
const {timestamp, vehicles} = frame || {};
const valid =
Number.isFinite(timestamp) &&
Array.isArray(vehicles) &&
vehicles.every(
(item) =>
item &&
typeof item.vehicleId === 'string' &&
Number.isFinite(item.longitude) &&
Number.isFinite(item.latitude) &&
Number.isFinite(item.heading) &&
Math.abs(item.longitude) <= 180 &&
Math.abs(item.latitude) <= 90 &&
(item.altitude === undefined || Number.isFinite(item.altitude)) &&
['car', 'bus'].includes(item.category),
);
if (!valid) {
info.textContent = '消息格式无效,请核对车辆字段和毫秒时间戳';
return;
}
if (timestamp <= latestTime || Math.abs(Date.now() - timestamp) > 30000) {
info.textContent = '时间戳过期或乱序,请检查服务端时钟';
return;
}
latestTime = timestamp;
twin.push(
vehicles.map((item) => ({
...item,
altitude: item.altitude ?? 0,
timestamp,
})),
);
if (!addressError) {
info.textContent = `${source} · ${vehicles.length} 辆车 · ${new Date(timestamp).toLocaleTimeString()}`;
}
}
operate.querySelector('#connect').onclick = () => {
try {
const url = new URL(stream.value);
if (!['ws:', 'wss:'].includes(url.protocol)) {
throw new Error();
}
stopFeed();
const connection = new WebSocket(url);
socket = connection;
info.textContent = '正在连接车流…';
connection.onopen = () => {
if (socket === connection) info.textContent = '已连接,等待位置帧…';
};
connection.onmessage = ({data}) => {
if (socket !== connection) return;
try {
acceptFrame(JSON.parse(data), '实时车流');
} catch {
info.textContent = '消息无法解析,请发送 UTF-8 JSON 文本';
}
};
connection.onerror = () => {
if (socket === connection) info.textContent = '连接失败,请检查地址、证书或服务状态';
};
connection.onclose = ({wasClean}) => {
if (socket === connection && wasClean) info.textContent = '车流连接已关闭';
};
} catch {
addressError = true;
info.textContent = '请输入可访问的 WebSocket 地址;HTTPS 页面请用 wss://';
}
};
// 回放源和真实服务使用同一种消息结构,每条消息是一帧完整车辆快照。
// 小范围内用局部米制换算计算路径距离和航向。
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',
})),
};
}
function playLocal() {
addressError = false;
stopFeed();
acceptFrame(makeFrame(), '本地回放');
frameTimer = setInterval(() => acceptFrame(makeFrame(), '本地回放'), 250);
}
operate.querySelector('#local').onclick = playLocal;
playLocal();
window.addEventListener('pagehide', ({persisted}) => {
if (!persisted) {
stopFeed();
engine.dispose();
}
});
通过 Twin 和 WebSocket 接收完整车辆位置帧,渲染写实轿车与公交车。默认沿景山公园周边道路本地回放。连接业务 WSS 时,服务端须按示例提供 JSON 字段和 BD-09 经纬度。
预览