您可以通过以下两种方式在 <gmp-map-3d> 元素上计算和呈现路线:
- 以声明方式使用
Route3DElement(<gmp-route-3d>):添加一个 Web 组件,用于向 Routes API 请求路线,并渲染 3D 路线多段线、起点和终点标记以及路线摘要弹出式窗口。 - 以编程方式使用
Route辅助方法:当您需要中间航点、自定义字段掩码或自定义多段线样式时,请调用Route.computeRoutes并将路线传递给create3DPolylines、createWaypointMarkers和createPopover。
这两种方法均可在 Maps JavaScript API 的 v=beta 渠道中使用。如需了解如何加载 Beta 渠道,请参阅版本控制。
前提条件和结算
在显示 3D 路线之前,请先设置 Google Cloud 项目,并为该项目同时启用 Maps JavaScript API 和 Routes API。加载 maps3d 和 routes 库。
渲染 <gmp-map-3d> 需按动态 3D 地图(Immersive Maps Pro)付费。
<gmp-route-3d> 或 Route.computeRoutes 发出的每个路线请求都会根据所请求的功能,按 Routes API Compute Routes SKU 计费:
| 配置 | 路线 SKU 层级 |
|---|---|
默认路线请求(TRAFFIC_UNAWARE,或不含路况多段线的 WALKING、BICYCLING 和 TRANSIT 出行方式)
|
计算路线基本功能版 |
routing-preference 设置为 traffic-aware 或 traffic-aware-optimal,且 traffic-polylines-disabled 已启用
|
计算路线专业版 |
routing-preference 设置为 traffic-aware 或 traffic-aware-optimal,并启用了用颜色表示路况的多段线(设置了路况感知偏好设置时的默认设置)
|
Compute Routes Enterprise |
如需了解 SKU 详情,请参阅 Maps JavaScript API 用量和结算。
使用 HTML 添加 3D 路线
如需使用最少的代码显示起点和终点之间的路线,请将 <gmp-route-3d> 嵌套在 <gmp-map-3d> 中,并添加 autofits-camera,以便地图自动框定路线:
<gmp-map-3d
style="height: 400px; width: 100%;"
mode="hybrid">
<gmp-route-3d
origin="Space Needle, Seattle, WA"
destination="Tacoma Dome, Tacoma, WA"
travel-mode="driving"
routing-preference="traffic-aware"
autofits-camera>
</gmp-route-3d>
</gmp-map-3d>
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&libraries=maps3d,routes">
</script>
将 YOUR_API_KEY 替换为您的 Google Maps Platform API 密钥。
Route3DElement 会自动将其多段线和摘要弹出式窗口颜色与父级 <gmp-map-3d> 的浅色或深色配色方案相匹配,并支持以下属性:
origin和destination:接受"lat,lng"坐标字符串、地点资源名称(例如"places/ChIJ-bfVTh8VkFQRDZLQnmioK9s")或地址字符串。在 JavaScript 中,这些属性还接受LatLng、LatLngLiteral、LatLngAltitude、LatLngAltitudeLiteral和Place对象。travel-mode(travelMode):接受driving(默认)、walking、bicycling或transit(呈现多模式步行和公交路线段)。routing-preference(routingPreference):接受traffic-unaware、traffic-aware或traffic-aware-optimal。traffic-polylines-disabled(trafficPolylinesDisabled):在考虑路况的路线中停用根据车速显示多段线颜色的功能,以便按 Compute Routes Pro 而非 Compute Routes Enterprise 对请求计费。departure-time(departureTime):接受 HTML 中的 ISO 8601 时间戳字符串(例如"2027-03-15T16:00:00Z")或 JavaScript 中的Date对象。autofits-camera(autofitsCamera):在<gmp-map-3d>视口中框定加载的路线。
处理路线事件并读取路线数据
Route3DElement 会在路线完成渲染时分派 gmp-load,在路线计算失败或返回零条路线时分派 gmp-error。gmp-load 触发后,您可以读取计算出的 routes、fallbackInfo 和 geocodingResults 属性:
const routeElement = document.querySelector('gmp-route-3d');
routeElement.addEventListener('gmp-load', () => {
const primaryRoute = routeElement.routes?.[0];
console.log('Distance (m):', primaryRoute?.distanceMeters);
console.log('Duration:', primaryRoute?.localizedValues?.duration);
});
routeElement.addEventListener('gmp-error', () => {
console.error('Failed to load the 3D route.');
});
何时使用路线辅助方法,而不是 gmp-route-3d
<gmp-route-3d> 使用默认标记和多段线样式呈现单个 origin 和 destination 之间的主要路线。当您需要中间航点、备选路线选择、自定义响应字段掩码或自定义多段线和标记样式时,请将 Route.computeRoutes 与 3D 辅助方法结合使用。
使用 Route 类自定义 3D 路线渲染
对于自定义 3D 路线工作流,请调用 Route.computeRoutes,并使用其 3D 辅助方法将返回的 Route 实例渲染到 <gmp-map-3d> 上:
<div id="map-container" style="height: 400px; width: 100%;"></div>
<script>
async function initMap() {
const { Map3DElement, MapMode } =
await google.maps.importLibrary('maps3d');
const { Route } = await google.maps.importLibrary('routes');
const map = new Map3DElement({
mode: MapMode.HYBRID,
});
document.getElementById('map-container').append(map);
const { routes } = await Route.computeRoutes({
origin: '1800 Amphibious Blvd., Mountain View, CA 94045',
destination: 'San Francisco Ferry Building, San Francisco, CA',
travelMode: 'DRIVING',
routingPreference: 'TRAFFIC_AWARE',
extraComputations: ['TRAFFIC_ON_POLYLINE'],
fields: ['path', 'speedPaths', 'localizedValues'],
});
const route = routes?.[0];
if (!route) return;
const [polylines, markers, popover] = await Promise.all([
route.create3DPolylines({
polylineOptions: {
strokeWidth: 10,
autofitsCamera: true,
},
}),
route.createWaypointMarkers(),
route.createPopover(),
]);
map.append(...polylines, ...markers, popover);
}
</script>
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&loading=async&callback=initMap">
</script>
将 YOUR_API_KEY 替换为您的 Google Maps Platform API 密钥。
为您调用的每个辅助方法在 ComputeRoutesRequest.fields 中添加必需字段:
create3DPolylines:对于标准多段线,请求'path'或'legs';当travelMode为'TRANSIT'时,请求'path'和'legs';对于用颜色表示路况的多段线,请求'speedPaths'和extraComputations: ['TRAFFIC_ON_POLYLINE']。传递RoutePolyline3DOptions以自定义polylineOptions或设置trafficPolylinesDisabled。createWaypointMarkers:在fields中请求'path'。创建起点和终点标记(默认为Marker3DElement,或者在CreateWaypointMarkersOptions中使用markerClass指定时为MarkerElement、MarkerInteractiveElement或Marker3DInteractiveElement)。此方法不会生成中间航点。createPopover:请求'path'和'localizedValues'(对于公交路线,还需请求'legs'),以便在路线路径的中点锚定摘要PopoverElement。