使用 Routes API 呼叫 computeRouteMatrix 方法 (REST) 或串流 ComputeRouteMatrix 方法 (gRPC),藉此計算多個起點和目的地的路徑距離和所需時間。
若有指定起點與目的地的組合,這些方法會計算從每個起點到終點結束的路線路徑距離和所需時間。
要求限制
Compute Route Matrix 方法強制執行以下要求限制:
元素數量 (起點數 × 目的地數) 不能超過 625。
如果指定
TRAFFIC_AWARE_OPTIMAL
,則元素數量不會超過 100。如要進一步瞭解TRAFFIC_AWARE_OPTIMAL
,請參閱設定品質和延遲時間一文。可使用地點 ID 可指定的路線控點 (出發地 + 目的地) 數量上限為 50。
回應錯誤
Compute Route Matrix 方法的一個特徵是,針對整個回應或個別回應元素可以傳回錯誤。舉例來說,如果要求格式錯誤 (例如要求為零),則整個回應都會發生錯誤。
但是,如果錯誤適用於回應中的部分元素 (例如,無法針對起點和目的地組合計算路徑),則只有受到錯誤影響的元素會傳回錯誤代碼。
串流結果
ComputeRouteMatrix gRPC 方法採用來源和目的地清單,並傳回包含每個來源和目的地組合路線資訊的串流。由於結果會以串流的形式傳回,因此您不必等到所有可能的路徑組合都經過計算後才能開始處理結果。
串流傳回的元素不保證會依任何順序傳回。因此,每個回應元素都包含 origin_index
和 destination_index
。針對要求指定的起點和目的地,路徑起點相當於特定元素的 origins[origin_index]
,路徑目的地則等於 destinations[destination_index]
。這些陣列為零索引。請務必儲存來源和目的地清單順序。
計算路徑矩陣範例
在 HTTP 要求中使用 computeRouteMatrix 方法來計算路徑矩陣。
HTTP 範例
以下範例顯示 computeRouteMatrix
HTTP 要求。在這個範例中,您:
指定兩個起點和兩個目的地路線控點的陣列。這個方法會計算從起點到各個目的地的路徑,而回應中包含四個路徑。
在陣列中,第一個元素的索引為 0,第二個元素為索引 1,依此類推。
加入回應欄位遮罩,以指定要傳回的回應 (REST) 或 ComputeRoutesResponse (gRPC) 欄位。在此範例中,將要求設定為針對每條路徑傳回
originIndex
、destinationIndex
、duration
、distanceMeters
、status
和condition
。詳情請參閱選擇要傳回的欄位一文。
curl -X POST -d '{ "origins": [ { "waypoint": { "location": { "latLng": { "latitude": 37.420761, "longitude": -122.081356 } } }, "routeModifiers": { "avoid_ferries": true} }, { "waypoint": { "location": { "latLng": { "latitude": 37.403184, "longitude": -122.097371 } } }, "routeModifiers": { "avoid_ferries": true} } ], "destinations": [ { "waypoint": { "location": { "latLng": { "latitude": 37.420999, "longitude": -122.086894 } } } }, { "waypoint": { "location": { "latLng": { "latitude": 37.383047, "longitude": -122.044651 } } } } ], "travelMode": "DRIVE", "routingPreference": "TRAFFIC_AWARE" }' \ -H 'Content-Type: application/json' -H 'X-Goog-Api-Key: YOUR_API_KEY' \ -H 'X-Goog-FieldMask: originIndex,destinationIndex,duration,distanceMeters,status,condition' \ 'https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix'
回應中包含所有可能的目的地和目的地路線控點的可能路徑。
透過 originIndex
和 destinationIndex
回應欄位,識別回應中的每個路徑。例如,回應中 1 的 originIndex
會對應至由要求中 origins
陣列索引 1 路線控點計算的路線。
[ { "originIndex": 0, "destinationIndex": 0, "status": {}, "distanceMeters": 822, "duration": "160s", "condition": "ROUTE_EXISTS" }, { "originIndex": 1, "destinationIndex": 0, "status": {}, "distanceMeters": 2919, "duration": "361s", "condition": "ROUTE_EXISTS" }, { "originIndex": 1, "destinationIndex": 1, "status": {}, "distanceMeters": 5598, "duration": "402s", "condition": "ROUTE_EXISTS" }, { "originIndex": 0, "destinationIndex": 1, "status": {}, "distanceMeters": 7259, "duration": "712s", "condition": "ROUTE_EXISTS" } ]
gRPC 範例
如需 gRPC 要求的範例,請參閱gRPC 要求範例的範例。該網頁上的 Java 範例會同時呼叫 Compute Routes 和 Compute Route Matrix。