路線是指從起點到終點的可導航路徑。你可以選擇取得不同交通方式的路線,例如步行、騎單車或不同類型的車輛。你也可以要求路線詳細資料,例如距離、預估導航時間、預期通行費,以及路線的逐步導航指示。
查看完整範例原始碼
下列程式碼範例說明如何取得兩個地點之間的行車路線。
TypeScript
// Initialize and add the map. let map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap(): Promise<void> { // Request the needed libraries. const [{Map}, {Place}, {Route}] = await Promise.all([ google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>, google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>, //@ts-ignore google.maps.importLibrary('routes') as Promise<google.maps.Routes> ]); map = new Map(document.getElementById("map") as HTMLElement, { zoom: 12, center: center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = {lat: 37.422000, lng: -122.084058}; // San Francisco, CA const destinationLatLng = {lat: 37.774929, lng: -122.419415}; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const {routes, fallbackInfo, geocodingResults} = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => polyline.setMap(map)); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => marker.setMap(map)); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
JavaScript
// Initialize and add the map. let map; let mapPolylines = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), //@ts-ignore google.maps.importLibrary('routes') ]); map = new Map(document.getElementById("map"), { zoom: 12, center: center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => polyline.setMap(map)); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => marker.setMap(map)); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. fitMapToPath(routes[0].path); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Get directions</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta"});</script>
</body>
</html>試用範例
呼叫 computeRoutes() 方法,要求兩個地點之間的路線。以下範例說明如何定義要求,然後呼叫 computeRoutes() 取得路線。
// Import the Routes library. const { Route } = await google.maps.importLibrary('routes'); // Define a computeRoutes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
選擇要傳回的欄位
要求路線時,您必須使用欄位遮罩指定回應應傳回的資訊。您可以在欄位遮罩中指定路線類別屬性的名稱。
使用欄位遮罩也能確保您不會要求不必要的資料,進而縮短回應延遲時間,並避免傳回系統不需要的資訊。
設定 ComputeRoutesRequest.fields 屬性,指定所需欄位清單,如下方程式碼片段所示:
TypeScript
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
指定路線的地點
如要計算路線,您至少必須指定路線起點和路線目的地的位置,以及欄位遮罩。您也可以在路線中指定中途路線控點,並使用路線控點執行其他動作,例如在路線中新增停靠點或直通點。
在 ComputeRoutesRequest 中,可以透過下列任一方式指定位置:
您可以為要求中的所有中途點指定相同的位置,也可以混用。 舉例來說,您可以為起點航點使用經緯度座標,並為目的地航點使用 Place 物件。
為提升效率和準確度,請使用 Place 物件,而非經緯度座標或地址字串。地點 ID 具有明確的唯一性,可提供地理編碼優勢,用於規劃路線,例如存取點和交通變數。這有助於避免因其他指定位置的方式而導致下列情況:
- 使用經緯度座標可能會導致系統將位置資訊對應到最接近這些座標的道路,但這可能不是房源的入口,甚至不是能快速或安全抵達目的地的道路。
- 地址字串必須先由 Routes API 進行地理編碼,轉換為經緯度座標,才能計算路徑。這項轉換可能會影響成效。
將地點指定為 Place 物件 (建議)
如要使用地點指定位置,請建立新的 Place 執行個體。下列程式碼片段顯示如何為 origin 和 destination 建立新的 Place 執行個體,然後在 ComputeRoutesRequest 中使用這些執行個體:
TypeScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
經緯度座標
如要將位置指定為經緯度座標,請建立新的 google.maps.LatLngLiteral、google.maps.LatLngAltitude 或 google.maps.LatLngAltitudeLiteral 例項。下列程式碼片段顯示如何為 origin 和 destination 建立新的 google.maps.LatLngLiteral 執行個體,然後在 computeRoutesRequest 中使用這些執行個體:
TypeScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = {lat: 37.422000, lng: -122.084058}; // San Francisco, CA const destinationLatLng = {lat: 37.774929, lng: -122.419415}; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
地址字串
地址字串是字串表示的實際地址 (例如「1600 Amphitheatre Parkway, Mountain View, CA」)。地理編碼是指將地址字串轉換為經緯度座標 (例如緯度 37.423021 和經度 -122.083739)。
將地址字串做為路徑點的位置傳遞時,Routes 程式庫會在內部對字串進行地理編碼,將其轉換為經緯度座標。
下列程式碼片段顯示如何為 origin 和 destination 建立含有地址字串的 ComputeRoutesRequest:
TypeScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
JavaScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
設定地址的區域
如果您傳遞不完整的地址字串做為中途點位置,API 可能會使用錯誤的地理編碼經緯度座標。舉例來說,您提出要求,將「Toledo」指定為行車路線的起點,「Madrid」指定為目的地:
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
在這個範例中,「Toledo」會解讀為美國俄亥俄州的城市,而非西班牙的城市。因此,要求會傳回空陣列,表示沒有任何路徑。
您可以加入 regionCode 參數,設定 API 優先傳回特定區域的結果。這個參數會指定區碼,採用 ccTLD (「頂層網域」) 的兩位字元值。大多數 ccTLD 代碼與 ISO 3166-1 代碼相同,但有一些需要注意的例外情況。舉例來說,英國的 ccTLD 是「uk」(.co.uk),而 ISO 3166-1 代碼是「gb」(技術上是指「大不列顛及北愛爾蘭聯合王國」實體)。
如果從「Toledo」到「Madrid」的路線要求包含 regionCode 參數,系統會將「Toledo」解讀為西班牙的城市,並傳回適當結果:
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
許多人沒有精確的地址,因此難以收到郵件或包裹。或者,有地址的使用者可能偏好在更明確的地點收貨,例如後門或裝卸貨碼頭。
Plus Code 就像是街道地址,適用於沒有實際地址的人或地點。 Plus code 是以經緯度座標為依據,並以數字和字母顯示,而非街道名稱和號碼。
Google 開發了 Plus Code,讓所有人都能享有地址的便利性。Plus Code 是經過編碼的位置參照,衍生自經緯度座標,表示面積不超過 1/8000 度 x 1/8000 度 (在赤道區約 14 公尺 x 14 公尺) 的區域。對於沒有詳細地址的地點,Plus Codes 可用於取代街道地址,例如無編號的建築物或無名街道。
Plus Code 必須採用全球代碼或複合代碼格式:
- 全球代碼是由 4 個半形字元的區碼,加上 6 個半形字元以上的地區代碼組成。舉例來說,如果地址是「1600 Amphitheatre Parkway, Mountain View, CA」,則全球代碼為「849V」,當地代碼為「CWC8+R9」。接著,您可以使用完整的 10 個字元 Plus Code,將位置值指定為「849VCWC8+R9」。
- 複合代碼是由 6 個半形字元以上的地區代碼,加上明確的位置組成。舉例來說,「450 Serra Mall, Stanford, CA 94305, USA」的當地代碼為「CRHJ+C3」。如果是複合地址,請將當地代碼與地址的城市、州/省、郵遞區號和國家/地區部分合併,格式為「CRHJ+C3 Stanford, CA 94305, USA」。
下列程式碼片段顯示如何使用 Plus Code 指定路線起點和目的地的途經點,藉此計算路線:
TypeScript
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };
JavaScript
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };