代码
import {
BaiduMapConfig,
BaiduVectorTileProvider,
Engine,
GeoJSONDataSource,
Polyline,
Label,
services,
urlUtils,
} from '@baidumap/mapv-three';
const ak = BaiduMapConfig.ak || '您的密钥';
const hasKey = ak.trim() && !ak.includes('密钥');
if (hasKey) {
BaiduMapConfig.ak = ak;
}
const provider = hasKey ? new BaiduVectorTileProvider({displayOptions: {poi: false}}) : null;
const engine = new Engine('map', {
map: {
projection: 'EPSG:3857',
center: [116.4035, 39.9175],
pitch: 0,
range: 11_000 / Math.min(1, document.getElementById('map').clientWidth / 580),
provider: provider,
},
});
const form = document.querySelector('#query');
const status = document.querySelector('#status');
if (!hasKey) {
status.textContent = '配置百度地图 AK 后可查询。';
}
const submit = document.querySelector('#submit');
const route = new services.TransitRoute({
apiSource: services.API_SOURCE_BAIDU,
});
const line = engine.add(
new Polyline({
color: '#1b75c9',
lineWidth: 5,
}),
);
const walkingLine = engine.add(
new Polyline({
color: '#ff9e32',
lineWidth: 4,
// 屏幕线采用 SDK 原生虚线节奏。
dashed: true,
}),
);
const marker = engine.add(
new Label({
type: 'icontext',
vertexIcons: true,
iconWidth: 23,
iconHeight: 37,
textAnchor: 'left',
textSize: 13,
textWeight: '600',
textFillStyle: '#18334a',
textStrokeStyle: '#ffffff',
textStrokeWidth: 3,
padding: [5, 4],
pixelOffset: [0, 17],
depthTest: false,
depthWrite: false,
}),
);
// 使用路线服务内置的起点、终点和公交图标。
const icon = {
start: urlUtils.getAssetUrl('assets/images/markers/mkr_start.png'),
end: urlUtils.getAssetUrl('assets/images/markers/mkr_end.png'),
};
function showRouteLabels(start, end, result) {
// 文字朝路线内部排布,给窄屏上的起终点留出空间。
const eastbound = start[0] <= end[0];
const labels = [
{
point: start,
text: result?.start?.title || '起点',
icon: icon.start,
textAnchor: eastbound ? 'left' : 'right',
},
{
point: end,
text: result?.end?.title || '终点',
icon: icon.end,
textAnchor: eastbound ? 'right' : 'left',
},
];
const shown = new Set([start.join(','), end.join(',')]);
const stations = new Set();
const midpoint = (start[0] + end[0]) / 2;
for (const step of result?.steps ?? []) {
if (!['bus', 'subway', 'train', 'airplane', 'car'].includes(step.type)) continue;
for (const stop of step.stops ?? []) {
const point = pointArray(stop.point);
const station = step.type + ':' + stop.title;
// 同站换乘时,合并重复的上车、下车标注。
if (!point || !stop.title || shown.has(point.join(',')) || stations.has(station)) continue;
shown.add(point.join(','));
stations.add(station);
labels.push({
point,
text: stop.title,
icon: urlUtils.getAssetUrl(`assets/images/markers/mkr_transit_${step.type}.png`),
iconSize: [21, 21],
textAnchor: point[0] <= midpoint ? 'left' : 'right',
});
}
}
showLabels(labels);
}
function showLabels(points) {
marker.visible = points.length > 0;
if (points.length) {
const source = GeoJSONDataSource.fromGeoJSON(
points.map(({point, text, icon, textAnchor, iconSize}) => ({
type: 'Feature',
geometry: {type: 'Point', coordinates: [...point, 5]},
properties: {text: shortText(text), icon, textAnchor, iconSize},
})),
);
source
.defineAttribute('text')
.defineAttribute('icon')
.defineAttribute('textAnchor')
.defineAttribute('iconSize');
marker.dataSource = source;
}
engine.requestRender();
}
function shortText(text) {
const chars = Array.from(text);
return chars.length > 14 ? chars.slice(0, 13).join('') + '…' : text;
}
function pointArray(point) {
const values = Array.isArray(point) ? point : [point?.x, point?.y];
const [lng, lat] = values;
return Number.isFinite(lng) && Number.isFinite(lat) ? [lng, lat] : null;
}
function readCoordinate(input) {
const values = input
.trim()
.split(/[,,]/)
.map((value) => value.trim());
const [lng, lat] = values.map(Number);
if (
values.length !== 2 ||
values.some((value) => !value) ||
!Number.isFinite(lng) ||
!Number.isFinite(lat) ||
Math.abs(lng) > 180 ||
Math.abs(lat) > 85
) {
return null;
}
return [lng, lat];
}
function showPaths(layer, paths) {
layer.visible = paths.length > 0;
if (paths.length) {
// 只为绘制添加高度,服务坐标和定位范围仍使用原有经纬度。
const positions = paths.map((path) => path.map(([lng, lat]) => [lng, lat, 5]));
layer.dataSource = GeoJSONDataSource.fromGeoJSON({
type: 'Feature',
geometry: {
type: 'MultiLineString',
coordinates: positions,
},
properties: {},
});
}
engine.requestRender();
}
function validPaths(paths) {
return (paths ?? [])
.map((path) => path.map(pointArray).filter(Boolean))
.filter((path) => path.length > 1);
}
// 示意线路只用于初始展示。实际线路使用服务返回的坐标。
const sample = [
[116.38, 39.907],
[116.383, 39.908],
[116.389, 39.908],
[116.398, 39.908],
[116.409, 39.908],
[116.419, 39.908],
[116.419, 39.916],
[116.42, 39.924],
[116.424, 39.928],
[116.427, 39.928],
];
showPaths(line, [sample.slice(1, -1)]);
showPaths(walkingLine, [sample.slice(0, 2), sample.slice(-2)]);
showRouteLabels(sample[0], sample.at(-1));
if (!hasKey) {
status.textContent = '示意路线 · 配置 AK 后可查询';
}
async function withTimeout(promise) {
let timer;
const timeout = new Promise((resolve, reject) => {
timer = setTimeout(() => reject(new Error('请求超时')), 12_000);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
form.addEventListener('submit', async (event) => {
event.preventDefault();
if (!hasKey) {
status.textContent = '示意路线 · 配置 AK 后可查询';
return;
}
const start = readCoordinate(form.elements.start.value);
const end = readCoordinate(form.elements.end.value);
if (!start || !end) {
status.textContent = '请输入两个有效的 BD-09 经纬度,格式为「经度, 纬度」。';
return;
}
if (start[0] === end[0] && start[1] === end[1]) {
status.textContent = '起点和终点需要是不同的位置。';
return;
}
submit.disabled = true;
status.textContent = '正在规划公交路线…';
showPaths(line, []);
showPaths(walkingLine, []);
showRouteLabels(start, end);
try {
const result = await withTimeout(route.search(start, end));
const paths = validPaths(result?.paths);
const walking = validPaths(result?.walkingPaths);
const coordinates = [...paths, ...walking].flat();
if (coordinates.length < 2) {
status.textContent = '未返回公交路线。请检查坐标及 AK 的服务权限。';
return;
}
showPaths(line, paths);
showPaths(walkingLine, walking);
const routeStart = pointArray(result.start?.point) ?? start;
const routeEnd = pointArray(result.end?.point) ?? end;
showRouteLabels(routeStart, routeEnd, result);
engine.map.setViewport([routeStart, routeEnd, ...coordinates], {
zoom: -1,
range: 1_500,
});
const distance = (result.distance / 1_000).toFixed(1);
const minutes = Math.max(1, Math.round(result.duration / 60));
status.textContent = `公交路线 ${distance} 公里,预计 ${minutes} 分钟。`;
} catch {
status.textContent = '公交路线规划失败,请检查网络及 AK 的服务权限。';
} finally {
submit.disabled = false;
}
});
调用 services.TransitRoute.search,以 BD-09 经纬度提交起点和终点,获取公交方案的预计耗时、距离和路线。示例先绘制一条示意路线,填写 AK 后可查询百度地图返回的实际路线。 蓝线表示公交或地铁,橙色虚线表示步行接驳。 缺少密钥时,以 OpenFreeMap 作预览底图,示意线路展示绘制效果。 用图文标注区分起点、终点和乘车站点。
预览