获取备选路线

欧洲经济区 (EEA) 开发者

Routes API 返回的默认路线通常是从起点到终点的最快路线。当您请求替代路线时,该 API 会返回一个数组,其中包含最多三条路线以及默认路线。然后,您的客户可以选择最适合自己的路线。

查看完整的示例源代码

以下代码示例展示了如何请求替代路线,然后在地图上绘制路线。

TypeScript

let mapPolylines: google.maps.Polyline[] = []; const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; let innerMap; // Initialize and add the map. async function initMap() {  // Request the needed libraries.  await google.maps.importLibrary('maps') as google.maps.MapsLibrary;  innerMap = mapElement.innerMap;  innerMap.setOptions({  mapTypeControl: false,  mapId: 'DEMO_MAP_ID',  });  // Call the function after the map is loaded.  google.maps.event.addListenerOnce(innerMap, 'idle', () => {  getDirections();  }); } async function getDirections() {  //@ts-ignore  // Request the needed libraries.  const [{ Route, RouteLabel }] = await Promise.all([  google.maps.importLibrary('routes')  ]);  // Build a request.  const request = {  origin: 'San Francisco, CA',  destination: 'Sunset Dr Pacific Grove, CA 93950',  travelMode: 'DRIVING',  computeAlternativeRoutes: true,  fields: ['path', 'routeLabels', 'viewport'], // Request the routeLabels field.  };  // Call computeRoutes to get the directions.  const result = await Route.computeRoutes(request);  if (!result.routes || result.routes.length === 0) {  console.warn("No routes found");  return;  }  let primaryRoute;  for (const route of result.routes) {  // Save the primary route for last so it's drawn on top.  if (  // Check for the default route.  route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE)  ) {  primaryRoute = route;  } else {  drawRoute(route, false);  }  }  if (primaryRoute) {  drawRoute(primaryRoute, true);  await primaryRoute.createWaypointAdvancedMarkers({ map: innerMap });  innerMap.fitBounds(primaryRoute.viewport, 50);  innerMap.setHeading(70);  }  // Display the raw JSON for the result in the console.  console.log(`Response:\n ${JSON.stringify(result, null, 2)}`); } function drawRoute(route, isPrimaryRoute) {  mapPolylines = mapPolylines.concat(  route.createPolylines({  polylineOptions: isPrimaryRoute  ? {  map: innerMap,  strokeWeight: 5,  }  : {  map: innerMap,  strokeColor: "#669DF6",  strokeOpacity: 0.5,  strokeWeight: 5,  },  colorScheme: innerMap.get("colorScheme"),  }),  ); } initMap();

JavaScript

let mapPolylines = []; const mapElement = document.querySelector('gmp-map'); let innerMap; // Initialize and add the map. async function initMap() {  // Request the needed libraries.  await google.maps.importLibrary('maps');  innerMap = mapElement.innerMap;  innerMap.setOptions({  mapTypeControl: false,  mapId: 'DEMO_MAP_ID',  });  // Call the function after the map is loaded.  google.maps.event.addListenerOnce(innerMap, 'idle', () => {  getDirections();  }); } async function getDirections() {  //@ts-ignore  // Request the needed libraries.  const [{ Route, RouteLabel }] = await Promise.all([  google.maps.importLibrary('routes')  ]);  // Build a request.  const request = {  origin: 'San Francisco, CA',  destination: 'Sunset Dr Pacific Grove, CA 93950',  travelMode: 'DRIVING',  computeAlternativeRoutes: true,  fields: ['path', 'routeLabels', 'viewport'], // Request the routeLabels field.  };  // Call computeRoutes to get the directions.  const result = await Route.computeRoutes(request);  if (!result.routes || result.routes.length === 0) {  console.warn("No routes found");  return;  }  let primaryRoute;  for (const route of result.routes) {  // Save the primary route for last so it's drawn on top.  if (  // Check for the default route.  route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE)) {  primaryRoute = route;  }  else {  drawRoute(route, false);  }  }  if (primaryRoute) {  drawRoute(primaryRoute, true);  await primaryRoute.createWaypointAdvancedMarkers({ map: innerMap });  innerMap.fitBounds(primaryRoute.viewport, 50);  innerMap.setHeading(70);  }  // Display the raw JSON for the result in the console.  console.log(`Response:\n ${JSON.stringify(result, null, 2)}`); } function drawRoute(route, isPrimaryRoute) {  mapPolylines = mapPolylines.concat(route.createPolylines({  polylineOptions: isPrimaryRoute  ? {  map: innerMap,  strokeWeight: 5,  }  : {  map: innerMap,  strokeColor: "#669DF6",  strokeOpacity: 0.5,  strokeWeight: 5,  },  colorScheme: innerMap.get("colorScheme"),  })); } 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> <gmp-map center="37.447646, -122.113878" zoom="10"></gmp-map> <!-- 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>

试用示例

请求备选路线时的注意事项

请求替代路线时,请考虑以下事项:

  • 您只能为没有中间途经点的路线请求替代路线。 当路线指定了中间航点时,请求备选路线不会导致错误。不过,系统不会返回任何替代路线。
  • 响应最多包含 3 条替代路线。不过,有时没有其他替代路线,因此响应仅包含默认路线。
  • 由于计算备选路线需要额外的处理,因此请求备选路线可能会增加 API 的响应时间。

请求备选路线

如需请求替代路线,请在 computeRoutes 请求中将 computeAlternativeRoutes 设置为 true

// Build a request. const request = {  origin: 'San Francisco, CA',  destination: 'Sunset Dr Pacific Grove, CA 93950',  travelMode: 'DRIVING',  computeAlternativeRoutes: true,  fields: ['path', 'routeLabels', 'viewport'], // Request the routeLabels field. };

如需获取路线,请遍历路线数组(例如 result.routes)。默认路线的路线标签为 RouteLabel.DEFAULT_ROUTE。以下代码示例展示了如何遍历路线,以及如何最后绘制主要路线。

// Call computeRoutes to get the directions. const result = await Route.computeRoutes(request); if (!result.routes || result.routes.length === 0) {  console.warn("No routes found");  return; } let primaryRoute; for (const route of result.routes) {  // Save the primary route for last so it's drawn on top.  if (  // Check for the default route.  route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE)) {  primaryRoute = route;  }  else {  drawRoute(route, false);  } } if (primaryRoute) {  drawRoute(primaryRoute, true);  await primaryRoute.createWaypointAdvancedMarkers({ map: innerMap });  innerMap.fitBounds(primaryRoute.viewport, 50);  innerMap.setHeading(70); }