路线矩阵是一个二维路线信息数组,其中行对应于出发地,列对应于目的地。给定一个出发地和目的地列表,Route Matrix 类会计算从每个出发地出发并到达每个目的地的路线的距离和时长。使用 Route Matrix 类计算多个出发地和目的地的路线距离和时长。
查看完整的示例源代码
此示例展示了如何使用 Route Matrix 类来计算多个出发地与目的地之间的行程距离和时长。
TypeScript
// Initialize and add the map. let map; let markers: google.maps.marker.AdvancedMarkerElement[] = []; let center = { lat: 51.55, lng: -1.8 }; async function initMap(): Promise<void> { // Request the needed libraries. //@ts-ignore const [{Map}, {Place}, {AdvancedMarkerElement, PinElement}, {RouteMatrix}] = await Promise.all([ google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>, google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>, google.maps.importLibrary('marker') as Promise<google.maps.MarkerLibrary>, google.maps.importLibrary('routes') as Promise<google.maps.RoutesLibrary> ]); const bounds = new google.maps.LatLngBounds(); map = new Map(document.getElementById('map') as HTMLElement, { zoom: 8, center: center, mapId: 'DEMO_MAP_ID', }); // Build the request using Place instances. const origin1 = new Place({ id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK }); const origin2 = new Place({ id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK }); const destinationA = new Place({ id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK }); const destinationB = new Place({ id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK }); await Promise.all([ origin1.fetchFields({ fields: ['location', 'displayName']}), origin2.fetchFields({ fields: ['location', 'displayName']}), destinationA.fetchFields({ fields: ['location', 'displayName']}), destinationB.fetchFields({ fields: ['location', 'displayName']}), ]); const request = { origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: 'DRIVING', units: google.maps.UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], }; // Show the request. (document.getElementById("request") as HTMLDivElement).innerText = JSON.stringify(request, null, 2); // Get the RouteMatrix response. const response = await RouteMatrix.computeRouteMatrix(request); // Show the response. (document.getElementById("response") as HTMLDivElement).innerText = JSON.stringify(response, null, 2); // Add markers for the origins. for (const origin of request.origins) { if (origin.location) { const pin = new PinElement({ //@ts-ignore glyphText: "O", glyphColor: "white", background: "#137333", borderColor: "white", }); const marker = new AdvancedMarkerElement({ map, position: origin.location, content: pin.element, title: `Origin: ${origin.displayName}`, }); markers.push(marker); bounds.extend(origin.location); } } // Add markers for the destinations. for (let i = 0; i < request.destinations.length; i++) { const destination = request.destinations[i]; if (destination.location) { const pin = new PinElement({ //@ts-ignore glyphText: "D", glyphColor: "white", background: "#C5221F", borderColor: "white", }); const marker = new AdvancedMarkerElement({ map, position: destination.location, content: pin.element, title: `Destination: ${destination.displayName}`, }); markers.push(marker); bounds.extend(destination.location); } } // Fit the map to the bounds of all markers. map.fitBounds(bounds); } initMap();
JavaScript
// Initialize and add the map. let map; let markers = []; let center = { lat: 51.55, lng: -1.8 }; async function initMap() { // Request the needed libraries. //@ts-ignore const [{ Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('marker'), google.maps.importLibrary('routes') ]); const bounds = new google.maps.LatLngBounds(); map = new Map(document.getElementById('map'), { zoom: 8, center: center, mapId: 'DEMO_MAP_ID', }); // Build the request using Place instances. const origin1 = new Place({ id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK }); const origin2 = new Place({ id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK }); const destinationA = new Place({ id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK }); const destinationB = new Place({ id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK }); await Promise.all([ origin1.fetchFields({ fields: ['location', 'displayName'] }), origin2.fetchFields({ fields: ['location', 'displayName'] }), destinationA.fetchFields({ fields: ['location', 'displayName'] }), destinationB.fetchFields({ fields: ['location', 'displayName'] }), ]); const request = { origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: 'DRIVING', units: google.maps.UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], }; // Show the request. document.getElementById("request").innerText = JSON.stringify(request, null, 2); // Get the RouteMatrix response. const response = await RouteMatrix.computeRouteMatrix(request); // Show the response. document.getElementById("response").innerText = JSON.stringify(response, null, 2); // Add markers for the origins. for (const origin of request.origins) { if (origin.location) { const pin = new PinElement({ //@ts-ignore glyphText: "O", glyphColor: "white", background: "#137333", borderColor: "white", }); const marker = new AdvancedMarkerElement({ map, position: origin.location, content: pin.element, title: `Origin: ${origin.displayName}`, }); markers.push(marker); bounds.extend(origin.location); } } // Add markers for the destinations. for (let i = 0; i < request.destinations.length; i++) { const destination = request.destinations[i]; if (destination.location) { const pin = new PinElement({ //@ts-ignore glyphText: "D", glyphColor: "white", background: "#C5221F", borderColor: "white", }); const marker = new AdvancedMarkerElement({ map, position: destination.location, content: pin.element, title: `Destination: ${destination.displayName}`, }); markers.push(marker); bounds.extend(destination.location); } } // Fit the map to the bounds of all markers. map.fitBounds(bounds); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #container { height: 100%; display: flex; } #sidebar { flex-basis: 15rem; flex-grow: 1; padding: 1rem; max-width: 30rem; height: 100%; box-sizing: border-box; overflow: auto; } #map { flex-basis: 0; flex-grow: 4; height: 100%; } #sidebar { flex-direction: column; }
HTML
<html>
<head>
<title>Route matrix</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="container">
<div id="map"></div>
<div id="sidebar">
<h3 style="flex-grow: 0">Request</h3>
<pre style="flex-grow: 1" id="request"></pre>
<h3 style="flex-grow: 0">Response</h3>
<pre style="flex-grow: 1" id="response"></pre>
</div>
</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>试用示例
请求限制
computeRouteMatrix 方法针对使用地址或 Place 实例的途径点以及项目强制执行以下请求限制。项是指路线矩阵中每个出发地与目的地之间的路线,因此项数等于出发地数量乘以目的地数量。例如,如果您有 10 个起点和 10 个目的地,则有 100 个项目:
- 对于非
TRANSIT路线,项目数量不得超过 625。 - 如果您指定了
TRANSIT路线,则商品数量不得超过 100。 - 如果您指定了
TRAFFIC_AWARE_OPTIMAL,则商品数量不得超过 100。 - 如果您使用地址或 Place 实例指定起点或终点,则最多可以指定 50 个。
如需了解详情,请参阅获取公交路线。
路线矩阵请求示例
以下示例展示了 ComputeRouteMatrixRequest。此示例执行以下操作:
- 显示了如何指定包含两个出发地和两个目的地的航点数组。该方法会计算从每个出发地到每个目的地的路线,因此响应包含四条路线。
在数组中,第一个元素的索引为 0,第二个元素的索引为 1,依此类推。 - 指定要返回的字段。在此示例中,请求配置为针对每条路线返回
durationMillis、distanceMeters和condition。
TypeScript
const request = { origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: 'DRIVING', units: google.maps.UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], };
JavaScript
const request = { origins: [origin1, origin2], destinations: [destinationA, destinationB], travelMode: 'DRIVING', units: google.maps.UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], };
响应包含所有起点和目的地途经点的组合对应的四条可能路线,如以下示例所示:
"matrix": { "rows": [ { "items": [ { "condition": "ROUTE_EXISTS", "distanceMeters": 202587, "durationMillis": 10040000 }, { "condition": "ROUTE_EXISTS", "distanceMeters": 252734, "durationMillis": 12240000 } ] }, { "items": [ { "condition": "ROUTE_EXISTS", "distanceMeters": 166135, "durationMillis": 6596000 }, { "condition": "ROUTE_EXISTS", "distanceMeters": 216282, "durationMillis": 8797000 } ] } ] }
使用出发地和目的地索引在二维数组中查找相应的 RouteMatrixItem,以标识结果中的每条路线。例如,描述从请求中索引为 1 的出发地到目的地 0 计算出的路线的 RouteMatrixItem 将位于 RouteMatrix.rows 数组的第 2 个元素和 RouteMatrixRow.items 数组的第 1 个元素中。
以下代码段展示了如何识别 RouteMatrixItem 以查找特定起点和目的地的路线:
// Find the route for origin 'x' and destination 'y'. const {matrix} = await RouteMatrix.computeRouteMatrix(request); const myRouteMatrixItem = matrix.rows[x].items[y];
选择要返回的字段
请求路线矩阵时,您必须使用字段掩码来指定响应应返回哪些信息。
使用字段掩码还可以确保您不会请求不必要的数据,这有助于缩短响应延迟时间,并避免返回系统不需要的信息。
通过设置
ComputeRoutesMatrixRequest.fields 属性来指定所需的字段列表,如以下代码段所示:
fields: ['durationMillis', 'distanceMeters', 'condition'],
确定要使用的字段掩码
下面介绍了如何确定要使用的字段,并为这些字段构建字段掩码:
- 使用
['*']的字段掩码请求所有字段。 - 在
RouteMatrixItem类中查看所需字段的层次结构。 使用上一步中显示的字段层次结构,以以下格式构建字段掩码:
topLevelField[.secondLevelField][.thirdLevelField][...]
例如,对于以下 RouteMatrixItem:
"travelAdvisory": { "fuelConsumptionMicroliters": 0, "tollInfo": { "estimatedPrices": [ { "currencyCode": "USD", "units": 4, "nanos": 400000000 } ] } },
如果您只想返回 RouteMatrixItem 的 tollInfo 字段,则字段掩码如下所示:
fields: ['travelAdvisory.tollInfo']
如果您想改为请求估计的燃料消耗量,则字段掩码如下所示:
fields: ['travelAdvisory.fuelConsumptionMicroliters']
如果您想同时请求这两个字段,则字段掩码如下所示:
fields: ['travelAdvisory.fuelConsumptionMicroliters', 'travelAdvisory.tollInfo']
如果您想请求获取全套旅行建议,您的字段遮盖如下所示:
fields: ['travelAdvisory']
请求公交路线矩阵
获取使用相应区域中可用的公共交通选项的公交路线矩阵。公交选项可能包括公交车、地铁和火车等。如需请求公交路线矩阵,请执行以下操作:
- 将
travelMode设置为TRANSIT。 - 请求
travelAdvisory字段。
详细了解公交路线。