要求路徑折線

歐洲經濟區 (EEA) 開發人員

computeRoutes 方法 (REST) 和 ComputeRoutes 方法 (gRPC) 都會傳回以折線表示的路徑,做為回應的一部分。這些 API 會傳回兩種折線:

  • 基本折線 (預設):代表路線,但折線中未嵌入車流量資訊。傳回基本折線的要求會以 Routes Basic 費率計費。進一步瞭解 Routes API 的帳單

  • 車流量監測折線:包含路線沿途的車流量狀況資訊。路況會以速度類別 (NORMALSLOWTRAFFIC_JAM) 表示,適用於折線的特定間隔。系統會以 Routes Preferred 費率,計算車流量感知折線的要求費用。進一步瞭解 Routes API 的計費方式。詳情請參閱「設定折線品質」。

如要進一步瞭解折線,請參閱:

要求路線、路段或步驟的基本折線

折線是以 Polyline (REST) 或 Polyline (gRPC) 物件表示。您可以在路線、路段和步驟層級,於回應中傳回折線。

使用回應欄位遮罩指定要傳回的折線:

  • 在路線層級,請在回應欄位遮罩中加入 routes.polyline,在回應中傳回折線。

  • 在路段層級,加入 routes.legs.polyline,即可在回應中傳回路線每個路段的折線。

  • 在步驟層級,請加入 routes.legs.steps.polyline,針對路段的每個步驟,在回應中傳回折線。

舉例來說,如要傳回整條路線、每個路段和每個路段中每個步驟的折線,請執行下列操作:

curl -X POST -d '{
  "origin":{
    "address": "1600 Amphitheatre Parkway, Mountain View, CA"
  },
  "destination":{
    "address": "24 Willie Mays Plaza, San Francisco, CA 94107"
  },
  "travelMode": "DRIVE"
}' \
-H 'Content-Type: application/json' \
-H 'X-Goog-Api-Key: YOUR_API_KEY' \
-H 'X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline,routes.legs.polyline,routes.legs.steps.polyline' \
'https://routes.googleapis.com/directions/v2:computeRoutes'

這項要求會傳回下列回應,其中包含路線、路線中每個路段,以及路段中每個步驟的折線:

{
  "routes": [
    {
      "legs": [
        {
          "polyline": {
              "encodedPolyline": "ipkcFfich...@Bs@?A?O?SD{A@o@B}@I?qA?_AA_@@_@?"
          }
        },
          "steps": [
              {
                  "polyline": {
                      "encodedPolyline": "kclcF...@sC@YIOKI"
                  }
              },
              {
                  "polyline": {
                      "encodedPolyline": "wblcF~...SZSF_@?"
                  }
              },
              ...
      ],
      "distanceMeters": 56901,
      "duration": "2420s",
      "polyline": {
        "encodedPolyline": "ipkcFfich...@Bs@?A?O?SD{A@o@B}@I?qA?_AA_@@_@?"
      }
    }
  ]
}

由於這項要求只包含起點和目的地,因此傳回的路徑只包含單一路段。因此,路段和路線的折線相同。

如果在要求中加入中途路線控點,傳回的路線會包含兩段路程:

curl -X POST -d '{
  "origin":{
    "address": "1600 Amphitheatre Parkway, Mountain View, CA"
  },
  "destination":{
    "address": "24 Willie Mays Plaza, San Francisco, CA 94107"
  },
  "intermediates": [
    { "address": "450 Serra Mall, Stanford, CA 94305, USA"},
  ],
  "travelMode": "DRIVE",
}' \
-H 'Content-Type: application/json' \
-H 'X-Goog-Api-Key: YOUR_API_KEY' \
-H 'X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline,routes.legs.polyline' \
'https://routes.googleapis.com/directions/v2:computeRoutes'

這項要求會傳回兩個路段,每個路段都有專屬的折線,以及整條路線的折線:

{
  "routes": [
    {
      "legs": [
        {
          "polyline": {
            "encodedPolyline": "kclcFfqchV?A...?I@G?GAECCCEKICBAFG"
          }
          "steps": [
            {
                "polyline": {
                    "encodedPolyline": "kclcFfqch...YIOKI"
                }
            },
        ...
        },
        {
          "polyline": {
            "encodedPolyline": "ojmcFtethV?K...QOYQOGA?_@MUG[Ga@G"
          }
          "steps": [
            {
                "polyline": {
                    "encodedPolyline": "uypeFbo`jVgJq...PoBiC"
                }
            },
        ...
        }
      ],
      "distanceMeters": 68403,
      "duration": "3759s",
      "polyline": {
          "encodedPolyline": "kclcFfqchV?A?CBKF[Ha...?GAECCCEKICBAFGJEBE"
      }
    }
  ]
}

折線品質

折線的品質可以用下列詞彙說明:

  • 點的浮點精確度

    點會指定為經緯度值,並以單精度浮點格式表示。這項做法適用於小值 (可精確表示),但由於浮點數四捨五入錯誤,值越大,精確度就越低。

    computeRoutes 方法 (REST) 和 ComputeRoutes 中,這項設定是由 polylineEncoding 控制。

  • 組成折線的點數

    點越多,折線越平滑 (尤其是曲線)。

    computeRoutes 方法 (REST) 和 ComputeRoutes 中,這項設定是由 polylineQuality 控制。

設定折線編碼類型

使用 polylineEncoding 請求選項控制折線類型。polylineEncoding 屬性會控制折線是否會編碼為 ENCODED_POLYLINE (預設值),也就是使用編碼折線演算法格式,或是 GEO_JSON_LINESTRING,也就是使用 GeoJSON LineString 格式

舉例來說,在要求主體中:

curl -X POST -d '{
  "origin":{
    "address": "1600 Amphitheatre Parkway, Mountain View, CA"
  },
  "destination":{
    "address": "24 Willie Mays Plaza, San Francisco, CA 94107"
  },
  "travelMode": "DRIVE",
  "polylineEncoding": "ENCODED_POLYLINE"
}' \
-H 'Content-Type: application/json' \
-H 'X-Goog-Api-Key: YOUR_API_KEY' \
-H 'X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline,routes.legs.polyline' \
'https://routes.googleapis.com/directions/v2:computeRoutes'

設定折線品質

polylineQuality 會將折線的品質指定為 HIGH_QUALITYOVERVIEW (預設值)。使用 OVERVIEW 時,折線是由少量點組成,且要求延遲時間比 HIGH_QUALITY 短。

舉例來說,在要求主體中:

{
  "origin":{
    "location":{
      "latLng":{
        "latitude": 37.419734,
        "longitude": -122.0827784
      }
    }
  },
  "destination":{
    "location":{
      "latLng":{
        "latitude": 37.417670,
        "longitude": -122.079595
      }
    }
  },
  "travelMode": "DRIVE",
  "routingPreference": "TRAFFIC_AWARE",
  "polylineQuality": "HIGH_QUALITY",
  "polylineEncoding": "ENCODED_POLYLINE",
  "departureTime": "2023-10-15T15:01:23.045123456Z",
  ...
}

要求提供可感知流量的折線

上述範例都會傳回基本折線,也就是沒有交通資訊的折線。此外,您也可以要求折線包含路線和路線各路段的交通資訊。

系統會根據路線沿途的路況資訊,在折線上顯示車流量。車流量狀況會以速度類別 (NORMALSLOWTRAFFIC_JAM) 表示,適用於回應折線的特定間隔。間隔是由起始 (含) 和結束 (不含) 折線點的索引定義。

舉例來說,下列回應顯示折線點 2 和 4 之間的 NORMAL 流量:

{
  "startPolylinePointIndex": 2,
  "endPolylinePointIndex": 4,
  "speed": "NORMAL"
}

如要要求計算考量流量的多邊形折線,請在要求中設定下列屬性:

  • extraComputations 陣列欄位設為 TRAFFIC_ON_POLYLINE,即可啟用流量計算功能。

  • travelMode 設為 DRIVETWO_WHEELER。如果要求使用其他交通方式,系統會傳回錯誤。

  • 在要求中指定 TRAFFIC_AWARETRAFFIC_AWARE_OPTIMAL 路由偏好設定。詳情請參閱「設定品質與延遲時間」。

  • 設定回應欄位遮罩,指定要傳回的回應屬性:

    • 在路線層級,在回應欄位遮罩中加入 routes.travelAdvisory,即可在回應中傳回所有旅遊資訊。如要只傳回流量資訊,請指定 routes.travelAdvisory.speedReadingIntervals

    • 在路段層級,在回應中加入 routes.legs.travelAdvisory,傳回路線每個路段的所有旅遊資訊。如要只傳回車流量資訊,請指定 routes.legs.travelAdvisory.speedReadingIntervals

curl -X POST -d '{
  "origin":{
    "address": "1600 Amphitheatre Parkway, Mountain View, CA"
  },
  "destination":{
    "address": "24 Willie Mays Plaza, San Francisco, CA 94107"
  },
  "travelMode": "DRIVE",
  "extraComputations": ["TRAFFIC_ON_POLYLINE"],
  "routingPreference": "TRAFFIC_AWARE_OPTIMAL"
}' \
-H 'Content-Type: application/json' \
-H 'X-Goog-Api-Key: YOUR_API_KEY' \
-H 'X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline,routes.legs.polyline,routes.travelAdvisory,routes.legs.travelAdvisory' \
'https://routes.googleapis.com/directions/v2:computeRoutes'

考量流量的折線回覆範例

在回應中,流量資料會編碼為折線,並包含在 travelAdvisory 欄位中,類型為 RouteLegTravelAdvisory 物件 (每個路段) 和 RouteTravelAdvisory 物件 (路線)。

例如:

{
  "routes": [
    {
      "legs": {
        "polyline": {
          "encodedPolyline": "}boeF~zbjVAg@EmB`GWHlD"
        },
        // Traffic data for the leg.
        "travelAdvisory": {
          "speedReadingIntervals": [
            {
              "endPolylinePointIndex": 1,
              "speed": "NORMAL"
            },
            {
              "startPolylinePointIndex": 1,
              "endPolylinePointIndex": 2,
              "speed": "SLOW"
            },
            {
              "startPolylinePointIndex": 2,
              "endPolylinePointIndex": 4,
              "speed": "NORMAL"
            }
          ] 
        }
      },
      "polyline": {
        "encodedPolyline": "}boeF~zbjVAg@EmB`GWHlD"
      },
      // Traffic data for the route.
      "travelAdvisory": {
        "speedReadingIntervals": [
          {
            "endPolylinePointIndex": 1,
            "speed": "NORMAL"
          },
          {
            "startPolylinePointIndex": 1,
            "endPolylinePointIndex": 2,
            "speed": "SLOW"
          },
          {
            "startPolylinePointIndex": 2,
            "endPolylinePointIndex": 4,
            "speed": "NORMAL"
          }
        ] 
      }
    }
  ]
}

RouteTravelAdvisoryRouteLegTravelAdvisory 都包含名為 speedReadingIntervals 的陣列欄位,其中含有車流速度資訊。陣列中的每個物件都以 SpeedReadingInterval (REST) 或 SpeedReadingInterval (gRPC) 物件表示。

SpeedReadingInterval 物件包含路線間隔的速讀資訊,例如 NORMALSLOWTRAFFIC_JAM。整個物件陣列涵蓋路線的整個折線,不會重疊。指定間隔的起點與前一個間隔的終點相同。

每個間隔都會以 startPolylinePointIndexendPolylinePointIndex 和對應的速度類別來描述。請注意,間隔中缺少開始索引,對應於 proto3 做法的索引 0。

startPolylinePointIndexendPolylinePointIndex 值不一定會連續。例如:

{
  "startPolylinePointIndex": 2,
  "endPolylinePointIndex": 4,
  "speed": "NORMAL"
}

在本例中,索引 2 到索引 4 的路況相同。

使用 Maps SDK 算繪考量交通狀況的折線

建議您使用 Google Maps SDK 提供的各種功能,在地圖上顯示可感知交通狀況的折線,包括自訂顏色、筆觸,以及沿著折線延伸的樣式。如要進一步瞭解如何使用折線,請參閱 Android 適用的折線功能iOS 適用的折線功能

折線的算繪範例

Maps SDK 使用者可定義速度類別與折線算繪架構之間的自訂對應邏輯。舉例來說,您可能會決定在 Google 地圖上以粗藍線顯示「正常」速度,以粗橘線顯示「緩慢」速度。

下列程式碼片段會針對墨爾本至伯斯的測地線段,加上粗的藍色折線。詳情請參閱「自訂外觀」(適用於 Android) 和「自訂折線」(適用於 iOS)。

Android

Java

Polyline line = map.addPolyline(new PolylineOptions()
    .add(new LatLng(-37.81319, 144.96298), new LatLng(-31.95285, 115.85734))
    .width(25)
    .color(Color.BLUE)
    .geodesic(true));

Kotlin

val line: Polyline = map.addPolyline(
  PolylineOptions()
    .add(LatLng(-37.81319, 144.96298), LatLng(-31.95285, 115.85734))
    .width(25f)
    .color(Color.BLUE)
    .geodesic(true)
)

iOS

Objective-C

GMSMutablePath *path = [GMSMutablePath path];
[path addLatitude:-37.81319 longitude:144.96298];
[path addLatitude:-31.95285 longitude:115.85734];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 10.f;
polyline.strokeColor = .blue;
polyline.geodesic = YES;
polyline.map = mapView;

Swift

let path = GMSMutablePath()
path.addLatitude(-37.81319, longitude: 144.96298)
path.addLatitude(-31.95285, longitude: 115.85734)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 10.0
polyline.geodesic = true
polyline.map = mapView

搭配「沿路線搜尋」功能使用編碼折線

使用 Places API Text Search 沿著計算路徑搜尋。您要將 Routes API Compute Routes 中預先計算的路線編碼折線,傳遞至 Text Search 要求。回覆會包含符合搜尋條件,且位於指定路線附近的地點。詳情請參閱「沿途搜尋」。

舉例來說,如要傳回起點和目的地之間的路線沿途咖啡廳:

Node.js

const API_KEY = 'YOUR_API_KEY';
const routes_service = 'https://routes.googleapis.com/directions/v2:computeRoutes';
const textSearch_service = 'https://places.googleapis.com/v1/places:searchText';

function init(){ const routes_request = { "origin":{ "address": "1600 Amphitheatre Parkway, Mountain View, CA" }, "destination":{ "address": "24 Willie Mays Plaza, San Francisco, CA 94107" }, "travelMode": "DRIVE" }; const textSearch_request = { "textQuery": "cafe", "searchAlongRouteParameters": { "polyline": { "encodedPolyline": "" } } }; fetchResources(routes_service,routes_request).then(routes => { textSearch_request.searchAlongRouteParameters.polyline.encodedPolyline = routes.routes[0].polyline.encodedPolyline; fetchResources(textSearch_service,textSearch_request).then(places => { console.log(places); }); }); } async function fetchResources(resource,reqBody){ const response = await fetch(resource, { method: 'POST', body: JSON.stringify(reqBody), headers: { 'Content-Type': 'application/json', 'X-Goog-Api-Key': API_KEY, 'X-Goog-FieldMask': '*' } }); const responseJSON = await response.json(); return responseJSON; } init();