查询路线

欧洲经济区 (EEA) 开发者

路线是指从起始位置(即出发地)到结束位置(即目的地)的可导航路径。您可以选择获取不同交通方式(例如步行、骑车或不同类型的车辆)的路线。您还可以请求路线详情,例如距离、预计的路线导航时间、预计的通行费以及路线导航的分步说明。

查看完整的示例源代码

以下代码示例展示了如何获取两个位置之间的驾车路线。

TypeScript

// Initialize and add the map. let map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap(): Promise<void> {  // Request the needed libraries.  const [{Map}, {Place}, {Route}] = await Promise.all([  google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>,  google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>,  //@ts-ignore  google.maps.importLibrary('routes') as Promise<google.maps.Routes>  ]);  map = new Map(document.getElementById("map") as HTMLElement, {  zoom: 12,  center: center,  mapTypeControl: false,  mapId: 'DEMO_MAP_ID',  });  // Use address strings in a directions request.  const requestWithAddressStrings = {  origin: '1600 Amphitheatre Parkway, Mountain View, CA',  destination: '345 Spear Street, San Francisco, CA',  fields: ['path'],  };  // Use Place IDs in a directions request.  const originPlaceInstance = new Place({  id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA  });  const destinationPlaceInstance = new Place({  id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA  });  const requestWithPlaceIds = {  origin: originPlaceInstance,  destination: destinationPlaceInstance,  fields: ['path'], // Request fields needed to draw polylines.  };   // Use lat/lng in a directions request.  // Mountain View, CA  const originLatLng = {lat: 37.422000, lng: -122.084058};  // San Francisco, CA  const destinationLatLng = {lat: 37.774929, lng: -122.419415};  // Define a computeRoutes request.  const requestWithLatLngs = {  origin: originLatLng,  destination: destinationLatLng,  fields: ['path'],  };  // Use Plus Codes in a directions request.  const requestWithPlusCodes = {  origin: '849VCWC8+R9', // Mountain View, CA  destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA  fields: ['path'],  };  // Define a routes request.  const request = {  origin: 'Mountain View, CA',  destination: 'San Francisco, CA',  travelMode: 'DRIVING',  fields: ['path'], // Request fields needed to draw polylines.  };  // Call computeRoutes to get the directions.  const {routes, fallbackInfo, geocodingResults} = await Route.computeRoutes(request);  // Use createPolylines to create polylines for the route.  mapPolylines = routes[0].createPolylines();  // Add polylines to the map.  mapPolylines.forEach((polyline) => polyline.setMap(map));  // Create markers to start and end points.  const markers = await routes[0].createWaypointAdvancedMarkers();  // Add markers to the map  markers.forEach((marker) => marker.setMap(map));  // Display the raw JSON for the result in the console.  console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`);  // Fit the map to the path.  fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path) {  const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary;  const bounds = new LatLngBounds();  path.forEach((point) => {  bounds.extend(point);  });  map.fitBounds(bounds); } initMap();

JavaScript

// Initialize and add the map. let map; let mapPolylines = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap() {  // Request the needed libraries.  const [{ Map }, { Place }, { Route }] = await Promise.all([  google.maps.importLibrary('maps'),  google.maps.importLibrary('places'),  //@ts-ignore  google.maps.importLibrary('routes')  ]);  map = new Map(document.getElementById("map"), {  zoom: 12,  center: center,  mapTypeControl: false,  mapId: 'DEMO_MAP_ID',  });  // Use address strings in a directions request.  const requestWithAddressStrings = {  origin: '1600 Amphitheatre Parkway, Mountain View, CA',  destination: '345 Spear Street, San Francisco, CA',  fields: ['path'],  };  // Use Place IDs in a directions request.  const originPlaceInstance = new Place({  id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA  });  const destinationPlaceInstance = new Place({  id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA  });  const requestWithPlaceIds = {  origin: originPlaceInstance,  destination: destinationPlaceInstance,  fields: ['path'], // Request fields needed to draw polylines.  };  // Use lat/lng in a directions request.  // Mountain View, CA  const originLatLng = { lat: 37.422000, lng: -122.084058 };  // San Francisco, CA  const destinationLatLng = { lat: 37.774929, lng: -122.419415 };  // Define a computeRoutes request.  const requestWithLatLngs = {  origin: originLatLng,  destination: destinationLatLng,  fields: ['path'],  };  // Use Plus Codes in a directions request.  const requestWithPlusCodes = {  origin: '849VCWC8+R9', // Mountain View, CA  destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA  fields: ['path'],  };  // Define a routes request.  const request = {  origin: 'Mountain View, CA',  destination: 'San Francisco, CA',  travelMode: 'DRIVING',  fields: ['path'], // Request fields needed to draw polylines.  };  // Call computeRoutes to get the directions.  const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request);  // Use createPolylines to create polylines for the route.  mapPolylines = routes[0].createPolylines();  // Add polylines to the map.  mapPolylines.forEach((polyline) => polyline.setMap(map));  // Create markers to start and end points.  const markers = await routes[0].createWaypointAdvancedMarkers();  // Add markers to the map  markers.forEach((marker) => marker.setMap(map));  // Display the raw JSON for the result in the console.  console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`);  // Fit the map to the path.  fitMapToPath(routes[0].path); } // Helper function to fit the map to the path. async function fitMapToPath(path) {  const { LatLngBounds } = await google.maps.importLibrary('core');  const bounds = new LatLngBounds();  path.forEach((point) => {  bounds.extend(point);  });  map.fitBounds(bounds); } 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> <div id="map"></div> <!-- 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>

试用示例

调用 computeRoutes() 方法以请求两个位置之间的路线。以下示例展示了如何定义请求,然后调用 computeRoutes() 以获取路线。

 // Import the Routes library.  const { Route } = await google.maps.importLibrary('routes');  // Define a computeRoutes request.  const request = {  origin: 'Mountain View, CA',  destination: 'San Francisco, CA',  };  // Call the computeRoutes() method to get routes.  const {routes} = await Route.computeRoutes(request);  

选择要返回的字段

请求路线时,您必须使用字段掩码来指定响应应返回哪些信息。您可以在字段掩码中指定路由类属性的名称。

使用字段掩码还可以确保您不会请求不必要的数据,这有助于缩短响应延迟时间,并避免返回系统不需要的信息。

通过设置 ComputeRoutesRequest.fields 属性来指定所需的字段列表,如以下代码段所示:

TypeScript

// Define a routes request. const request = {  origin: 'Mountain View, CA',  destination: 'San Francisco, CA',  travelMode: 'DRIVING',  fields: ['path'], // Request fields needed to draw polylines. };

JavaScript

// Define a routes request. const request = {  origin: 'Mountain View, CA',  destination: 'San Francisco, CA',  travelMode: 'DRIVING',  fields: ['path'], // Request fields needed to draw polylines. };

指定路线的位置

如需计算路线,您必须至少指定路线起点和路线终点的位置,以及一个字段掩码。您还可以指定路线上的中间航点,并使用航点执行其他操作,例如在路线上添加经停点或直达点。

ComputeRoutesRequest 中,您可以通过以下任一方式指定位置:

您可以采用相同的方式为请求中的所有途经点指定位置,也可以混合使用不同的方式。 例如,您可以为出发地航点使用纬度/经度坐标,为目的地航点使用 Place 对象。

为了提高效率和准确性,请使用 Place 对象,而不是纬度/经度坐标或地址字符串。地点 ID 具有唯一性,可为路线规划(例如出入口和交通变量)提供地理编码优势。它们有助于避免因采用其他指定位置的方式而可能导致的以下情况:

  • 使用纬度/经度坐标可能会导致系统将位置信息定位到距离这些坐标最近的道路,而该道路可能不是房产的入口点,甚至不是能快速或安全到达目的地的道路。
  • 地址字符串必须先通过 Routes API 进行地理编码,将其转换为纬度/经度坐标,然后才能计算路线。这种转换可能会影响效果。

将位置指定为 Place 对象(首选)

如需使用 Place 指定位置,请创建新的 Place 实例。以下代码段展示了如何为 origindestination 创建新的 Place 实例,然后在 ComputeRoutesRequest 中使用它们:

TypeScript

// Use Place IDs in a directions request. const originPlaceInstance = new Place({  id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({  id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = {  origin: originPlaceInstance,  destination: destinationPlaceInstance,  fields: ['path'], // Request fields needed to draw polylines. }; 

JavaScript

// Use Place IDs in a directions request. const originPlaceInstance = new Place({  id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({  id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = {  origin: originPlaceInstance,  destination: destinationPlaceInstance,  fields: ['path'], // Request fields needed to draw polylines. };

经纬度坐标

如需将某个位置指定为纬度/经度坐标,请创建新的 google.maps.LatLngLiteralgoogle.maps.LatLngAltitudegoogle.maps.LatLngAltitudeLiteral 实例。以下代码段展示了如何为 origindestination 创建新的 google.maps.LatLngLiteral 实例,然后在 computeRoutesRequest 中使用它们:

TypeScript

// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = {lat: 37.422000, lng: -122.084058}; // San Francisco, CA const destinationLatLng = {lat: 37.774929, lng: -122.419415}; // Define a computeRoutes request. const requestWithLatLngs = {  origin: originLatLng,  destination: destinationLatLng,  fields: ['path'], };

JavaScript

// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = {  origin: originLatLng,  destination: destinationLatLng,  fields: ['path'], };

地址字符串

地址字符串是指以字符串形式表示的实际地址(例如“1600 Amphitheatre Parkway, Mountain View, CA”)。地理编码是将地址字符串转换为纬度和经度坐标(例如,纬度 37.423021 和经度 -122.083739)的过程。

当您传递地址字符串作为途经点的位置时,Routes 库会在内部对该字符串进行地理编码,以将其转换为纬度和经度坐标。

以下代码段展示了如何创建 ComputeRoutesRequest,其中包含 origindestination 的地址字符串:

TypeScript

// Use address strings in a directions request. const requestWithAddressStrings = {  origin: '1600 Amphitheatre Parkway, Mountain View, CA',  destination: '345 Spear Street, San Francisco, CA',  fields: ['path'], };

JavaScript

// Use address strings in a directions request. const requestWithAddressStrings = {  origin: '1600 Amphitheatre Parkway, Mountain View, CA',  destination: '345 Spear Street, San Francisco, CA',  fields: ['path'], };

为地址设置区域

如果您传递不完整的地址字符串作为途经点的地理位置,API 可能会使用错误的地理编码经纬度坐标。例如,您发出请求,指定“托莱多”为驾车路线的出发地,“马德里”为目的地:

// Define a request with an incomplete address string. const request = {  origin: 'Toledo',  destination: 'Madrid', };  

在此示例中,“托莱多”被解读为美国俄亥俄州的一个城市,而不是西班牙的一个城市。因此,该请求会返回一个空数组,表示不存在任何路线。

您可以添加 regionCode 参数,将 API 配置为返回偏向特定地区的结果。此参数以 ccTLD(“顶级域名”)双字符值的形式指定地区代码。除了某些明显的例外情况之外,大多数 ccTLD 代码都与 ISO 3166-1 代码完全一致。例如,英国的 ccTLD 为“uk”(.co.uk),而其 ISO 3166-1 代码为“gb”(从技术上讲,是指“大不列颠及北爱尔兰联合王国”这一实体)。

从“托莱多”到“马德里”的路线请求(包含 regionCode 参数)会返回相应的结果,因为“托莱多”会被解读为西班牙的城市:

const request = {  origin: 'Toledo',  destination: 'Madrid',  region: 'es', // Specify the region code for Spain. };  

Plus Code

许多人没有确切的地址,这可能会导致他们难以收到送货。或者,有地址的用户可能更愿意在更具体的地点(例如后门或装货平台)接收送货。

Plus Code 就像是未分配实际地址的人员或地点的街道地址。 Plus Code 不使用包含街道名称和门牌号的地址,而是以纬度/经度坐标为依据,并以数字和字母的形式显示。

Google 开发了 Plus Codes, 旨在让所有人都能享受地址带来的便利。Plus 代码是经过编码的位置引用,衍生自纬度和经度坐标,表示面积不超过 1/8, 000 度 x 1/8, 000 度(在赤道处约为 14 米 x 14 米)的区域。在没有街道地址或建筑物未编号/街道未命名的地点,您可以使用 Plus Codes 代替街道地址。

Plus Code 必须采用全局代码或混合代码格式:

  • 全局代码由包含 4 个字符的区号和至少包含 6 个字符的区域代码组成。例如,对于地址“1600 Amphitheatre Parkway, Mountain View, CA”,全球代码为“849V”,本地代码为“CWC8+R9”。然后,您可以使用完整的 10 字符 Plus Code 将地理位置值指定为“849VCWC8+R9”。
  • 混合代码由至少包含 6 个字符的区域代码与明确的位置信息组合而成。例如,地址“450 Serra Mall, Stanford, CA 94305, USA”的本地代码为“CRHJ+C3”。对于复合地址,请将本地代码与地址的城市、州、邮政编码和国家/地区部分组合在一起,格式为“CRHJ+C3 Stanford, CA 94305, USA”。

以下代码段展示了如何使用 Plus Code 为路线起点和目的地指定途经点,从而计算路线:

TypeScript

// Use Plus Codes in a directions request. const requestWithPlusCodes = {  origin: '849VCWC8+R9', // Mountain View, CA  destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA  fields: ['path'], };

JavaScript

// Use Plus Codes in a directions request. const requestWithPlusCodes = {  origin: '849VCWC8+R9', // Mountain View, CA  destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA  fields: ['path'], };