请求路线多段线

欧洲经济区 (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 的用户有机会定义速度类别与多段线呈现架构之间的自定义映射逻辑。例如,用户可能会决定在地图上将“NORMAL”速度显示为粗蓝色线条,而将“SLOW”速度显示为粗橙色线条。

以下代码段将会添加一条蓝色的粗多段线,其中包含从墨尔本至珀斯的测地线段。如需了解详情,请参阅自定义 外观 (适用于 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 文本搜索功能沿计算出的路线进行搜索。您可以将预先计算出的路线的编码多段线从 Routes API Compute Routes 传递到文本搜索请求。然后,响应会包含符合搜索条件且位于指定路线附近的地点。如需了解详情,请参阅沿路线 搜索

例如,如需返回起点和目的地之间路线沿线的咖啡馆,请执行以下操作:

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();