Ma trận tuyến đường là một mảng hai chiều gồm thông tin về tuyến đường, trong đó các hàng tương ứng với điểm xuất phát và các cột tương ứng với điểm đến. Với danh sách các điểm xuất phát và điểm đến, lớp Ma trận tuyến đường sẽ tính toán khoảng cách và thời lượng của một tuyến đường bắt đầu tại mỗi điểm xuất phát và kết thúc tại mỗi điểm đến. Sử dụng lớp Ma trận tuyến đường để tính khoảng cách và thời lượng của một tuyến đường cho nhiều điểm xuất phát và điểm đến.
Xem mã nguồn ví dụ hoàn chỉnh
Ví dụ này cho biết cách sử dụng lớp Ma trận tuyến đường để tính toán khoảng cách và thời lượng di chuyển giữa nhiều điểm xuất phát và điểm đến.
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>Dùng thử mẫu
Giới hạn yêu cầu
Phương thức computeRouteMatrix áp dụng các giới hạn yêu cầu sau đây cho các điểm tham chiếu bằng cách sử dụng địa chỉ hoặc các thực thể Địa điểm và cho các mục. Các mục là tuyến đường giữa mỗi điểm xuất phát và điểm đến trong ma trận tuyến đường, vì vậy, số lượng mục là số lượng điểm xuất phát nhân với số lượng điểm đến. Ví dụ: nếu bạn có 10 điểm xuất phát và 10 điểm đến, thì bạn sẽ có 100 mục:
- Số lượng mặt hàng không được vượt quá 625 đối với những tuyến đường không phải là tuyến đường
TRANSIT. - Nếu bạn chỉ định một
TRANSITtuyến đường, thì số lượng mục không được vượt quá 100. - Nếu bạn chỉ định
TRAFFIC_AWARE_OPTIMAL, thì số lượng mặt hàng không được vượt quá 100. - Nếu chỉ định điểm xuất phát hoặc điểm đến bằng địa chỉ hoặc thực thể Địa điểm, bạn có thể chỉ định tối đa 50 điểm theo cách này.
Để biết thêm thông tin chi tiết, hãy xem bài viết Lấy tuyến đường đi phương tiện công cộng.
Ví dụ về yêu cầu ma trận tuyến đường
Ví dụ sau đây minh hoạ một ComputeRouteMatrixRequest. Ví dụ này thực hiện những việc sau:
- Cho biết cách chỉ định một mảng gồm 2 điểm tham chiếu của điểm xuất phát và 2 điểm tham chiếu của đích đến. Phương thức này tính toán một tuyến đường từ mỗi điểm xuất phát đến mỗi điểm đến, do đó, phản hồi chứa 4 tuyến đường.
Trong mảng, phần tử đầu tiên có chỉ mục là 0, phần tử thứ hai có chỉ mục là 1, v.v. - Chỉ định các trường cần trả về. Trong ví dụ này, yêu cầu được định cấu hình để trả về
durationMillis,distanceMetersvàconditioncho từng tuyến đường.
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'], };
Phản hồi chứa 4 tuyến đường có thể có cho tổ hợp tất cả các điểm tham chiếu của điểm xuất phát và điểm đến, như minh hoạ trong ví dụ sau:
"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 } ] } ] }
Xác định từng tuyến đường trong kết quả bằng cách sử dụng chỉ mục điểm bắt đầu và điểm đến để tìm RouteMatrixItem tương ứng trong mảng 2D. Ví dụ: RouteMatrixItem mô tả tuyến đường được tính từ điểm xuất phát ở chỉ mục 1 và điểm đến 0 trong yêu cầu sẽ nằm ở phần tử thứ 2 của mảng RouteMatrix.rows và phần tử thứ 1 của mảng RouteMatrixRow.items.
Đoạn mã sau đây cho thấy cách xác định RouteMatrixItem để tìm tuyến đường cho một điểm xuất phát và điểm đến cụ thể:
// Find the route for origin 'x' and destination 'y'. const {matrix} = await RouteMatrix.computeRouteMatrix(request); const myRouteMatrixItem = matrix.rows[x].items[y];
Chọn các trường cần trả về
Khi yêu cầu một ma trận tuyến đường, bạn phải sử dụng một mặt nạ trường để chỉ định thông tin mà phản hồi sẽ trả về.
Việc sử dụng mặt nạ trường cũng đảm bảo rằng bạn không yêu cầu dữ liệu không cần thiết, từ đó giúp giảm độ trễ phản hồi và tránh trả về thông tin mà hệ thống của bạn không cần.
Chỉ định danh sách các trường bạn cần bằng cách đặt thuộc tính
ComputeRoutesMatrixRequest.fields, như trong đoạn mã sau:
fields: ['durationMillis', 'distanceMeters', 'condition'],
Xác định những mặt nạ trường cần sử dụng
Sau đây là cách xác định những trường bạn muốn sử dụng và tạo mặt nạ trường cho các trường đó:
- Yêu cầu tất cả các trường bằng cách sử dụng mặt nạ trường
['*']. - Xem hệ thống phân cấp của các trường trong lớp
RouteMatrixItemcho các trường bạn muốn. Tạo mặt nạ trường bằng cách sử dụng hệ phân cấp của các trường xuất hiện ở bước trước, theo định dạng sau:
topLevelField[.secondLevelField][.thirdLevelField][...]
Ví dụ: đối với RouteMatrixItem này:
"travelAdvisory": { "fuelConsumptionMicroliters": 0, "tollInfo": { "estimatedPrices": [ { "currencyCode": "USD", "units": 4, "nanos": 400000000 } ] } },
Nếu bạn chỉ muốn trả về trường tollInfo cho RouteMatrixItem, thì mặt nạ trường của bạn sẽ như sau:
fields: ['travelAdvisory.tollInfo']
Nếu bạn muốn yêu cầu mức tiêu thụ nhiên liệu ước tính, thì mặt nạ trường của bạn sẽ như sau:
fields: ['travelAdvisory.fuelConsumptionMicroliters']
Nếu bạn muốn yêu cầu cả hai, thì mặt nạ trường của bạn sẽ như sau:
fields: ['travelAdvisory.fuelConsumptionMicroliters', 'travelAdvisory.tollInfo']
Và nếu bạn muốn yêu cầu toàn bộ bộ thông tin tư vấn du lịch, thì mặt nạ trường của bạn sẽ như sau:
fields: ['travelAdvisory']
Yêu cầu ma trận tuyến đường phương tiện công cộng
Nhận ma trận tuyến đường phương tiện công cộng sử dụng các lựa chọn về phương tiện công cộng có sẵn trong khu vực. Các lựa chọn về phương tiện công cộng có thể bao gồm xe buýt, tàu điện ngầm và tàu hoả, v.v. Cách yêu cầu ma trận tuyến đường giao thông công cộng:
- Thiết lập
travelModethànhTRANSIT - Yêu cầu trường
travelAdvisory.
Tìm hiểu thêm về tuyến đường giao thông công cộng.