请求路线多段线

欧洲经济区 (EEA) 开发者

computeRoutes 方法 (REST) 和 ComputeRoutes 方法 (gRPC) 都会返回以折线表示的路线,作为响应的一部分。这些 API 会返回两种类型的折线:

  • 基本多段线(默认),表示路线,但多段线中未嵌入路况信息。返回基本折线的请求按 Routes Basic 费率收费。详细了解 Routes API 的结算

  • 可感知路况的多段线,包含有关路线沿途路况的信息。路况信息以速度类别(NORMALSLOWTRAFFIC_JAM)表示,适用于折线的指定间隔。请求使用考虑路况的多段线的费用按“路线首选”费率结算。详细了解 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 和相应的速度类别描述。请注意,区间内缺少起始索引对应于索引 0,这符合 proto3 实践

startPolylinePointIndexendPolylinePointIndex 值并不总是连续的。例如:

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

在本例中,从指数 2 到指数 4,流量条件相同。

使用 Maps SDK 渲染具有流量感知功能的多段线

我们建议您使用 Google Maps SDK 提供的各种功能(包括自定义颜色、笔触和沿多段线延伸的图案)在地图上显示可感知路况的多段线。如需详细了解如何使用折线,请参阅 Android 版折线功能iOS 版折线功能

多段线渲染示例

Maps SDK 的用户有机会定义速度类别与多段线渲染架构之间的自定义映射逻辑。例如,用户可能会决定在地图上以粗蓝线显示“正常”速度,以粗橙线显示“慢”速度。

以下代码段将会添加一条蓝色的粗多段线,其中包含从墨尔本至珀斯的测地线段。如需了解详情,请参阅自定义外观(适用于 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();