您可以透過兩種方式,在 <gmp-map-3d> 元素上計算及算繪路線:
- 使用
Route3DElement(<gmp-route-3d>) 以宣告方式:新增網頁元件,向 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>的費用會計入 Dynamic 3D Maps (Immersive Maps Pro)。
<gmp-route-3d> 或 Route.computeRoutes 提出的每項路線要求,都會根據要求的特徵,以 Routes API Compute Routes SKU 計費:
| 設定 | Routes SKU 級別 |
|---|---|
預設路線要求 (TRAFFIC_UNAWARE,或 WALKING、BICYCLING 和 TRANSIT 交通方式,不含車流量折線) |
Compute Routes Essentials |
routing-preference 設為 traffic-aware 或 traffic-aware-optimal,且已啟用 traffic-polylines-disabled |
Compute Routes Pro |
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 地圖平台 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 地圖平台 API 金鑰。
針對您呼叫的每個輔助方法,在 ComputeRoutesRequest.fields 中加入必要欄位:
create3DPolylines:要求'path'或'legs'取得標準折線,要求'path'和'legs'(travelMode為'TRANSIT'時),或要求'speedPaths'和extraComputations: ['TRAFFIC_ON_POLYLINE']取得車流量顏色折線。傳遞RoutePolyline3DOptions來自訂polylineOptions或設定trafficPolylinesDisabled。createWaypointMarkers:在fields中要求'path'。建立起點和目的地標記 (預設為Marker3DElement,或在CreateWaypointMarkersOptions中使用markerClass指定時,則為MarkerElement、MarkerInteractiveElement或Marker3DInteractiveElement)。這個方法不會產生中途路線控點。createPopover:要求'path'和'localizedValues'(如果是遞移路由,則加上'legs'),將摘要PopoverElement錨定在路線路徑的中間。