代码
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.397, 39.919],
pitch: 0,
range: 5_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.WalkingRoute({
apiSource: services.API_SOURCE_BAIDU,
});
const line = engine.add(
new Polyline({
color: '#11a38e',
lineWidth: 5,
}),
);
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',
},
];
showLabels(labels);
}
function showLabels(points) {
marker.visible = points.length > 0;
if (points.length) {
const source = GeoJSONDataSource.fromGeoJSON(
points.map(({point, text, icon, textAnchor}) => ({
type: 'Feature',
geometry: {type: 'Point', coordinates: [...point, 5]},
properties: {text: shortText(text), icon, textAnchor},
})),
);
source.defineAttribute('text').defineAttribute('icon').defineAttribute('textAnchor');
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.396, 39.911],
[116.396, 39.914],
[116.394, 39.915],
[116.395, 39.917],
[116.399, 39.918],
[116.398, 39.923],
[116.398, 39.927],
];
showPaths(line, [sample]);
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, []);
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, ...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.WalkingRoute.search,以 BD-09 经纬度提交起点和终点,获取步行方案的预计耗时、距离和路线。示例先绘制一条示意路线,填写 AK 后可查询百度地图返回的实际路线。 缺少密钥时,以 OpenFreeMap 作预览底图,示意线路展示绘制效果。 用图文标注区分起点和终点。
预览