Tuyến đường mặc định do Routes API trả về thường là tuyến đường nhanh nhất từ điểm khởi hành đến điểm đến. Khi bạn yêu cầu các tuyến đường thay thế, API sẽ trả về một mảng gồm tối đa 3 tuyến đường cùng với tuyến đường mặc định. Sau đó, khách hàng có thể chọn tuyến đường phù hợp nhất với họ.
Xem mã nguồn ví dụ hoàn chỉnh
Mã mẫu sau đây cho biết cách yêu cầu các tuyến đường thay thế, sau đó vẽ các tuyến đường đó trên bản đồ.
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>Thử dùng mẫu
Những điều cần cân nhắc khi yêu cầu tuyến đường thay thế
Khi yêu cầu các tuyến đường thay thế, hãy cân nhắc những điều sau:
- Bạn chỉ có thể yêu cầu các tuyến đường thay thế cho những tuyến đường không có điểm tham chiếu trung gian. Việc yêu cầu các tuyến đường thay thế khi tuyến đường chỉ định các điểm tham chiếu trung gian không gây ra lỗi. Tuy nhiên, không có tuyến đường thay thế nào được trả về.
- Phản hồi chứa tối đa 3 tuyến đường thay thế. Tuy nhiên, đôi khi không có tuyến đường thay thế nào, nên phản hồi chỉ chứa tuyến đường mặc định.
- Do cần thêm quy trình xử lý để tính toán các tuyến đường thay thế, nên việc yêu cầu các tuyến đường thay thế có thể làm tăng thời gian phản hồi của API.
Yêu cầu tuyến đường thay thế
Để yêu cầu các tuyến đường thay thế, hãy đặt computeAlternativeRoutes thành true trong yêu cầu computeRoutes.
// 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. };
Để lấy các tuyến đường, hãy lặp lại mảng tuyến đường (ví dụ: result.routes). Tuyến đường mặc định có nhãn tuyến đường là RouteLabel.DEFAULT_ROUTE. Mẫu mã sau đây cho thấy cách lặp lại các tuyến đường và vẽ tuyến đường chính sau cùng.
// 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); }