आम तौर पर, Routes API से मिलने वाला डिफ़ॉल्ट रूट, ऑरिजन से डेस्टिनेशन तक का सबसे तेज़ रूट होता है. अन्य रूट का अनुरोध करने पर, एपीआई डिफ़ॉल्ट रूट के साथ-साथ, ज़्यादा से ज़्यादा तीन रूट का कलेक्शन दिखाता है. इसके बाद, आपके ग्राहक अपनी ज़रूरत के हिसाब से कोई रूट चुन सकते हैं जो उनके लिए सबसे अच्छा हो.
सोर्स कोड का पूरा उदाहरण देखें
यहां दिए गए कोड के सैंपल में, अन्य रूट का अनुरोध करने और फिर उन्हें मैप पर दिखाने का तरीका बताया गया है.
TypeScript
const mapPolylines: google.maps.Polyline[] = []; const mapElement = document.querySelector('gmp-map')!; let innerMap: google.maps.Map; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // Request the needed libraries. const [{ Route, RouteLabel }] = await Promise.all([ google.maps.importLibrary('routes'), ]); // Build a request. const request: google.maps.routes.ComputeRoutesRequest = { 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: google.maps.routes.Route | undefined; 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: google.maps.routes.Route, isPrimaryRoute: boolean) { mapPolylines.push( ...route.createPolylines({ polylineOptions: isPrimaryRoute ? { map: innerMap, strokeWeight: 5, } : { map: innerMap, strokeColor: '#669DF6', strokeOpacity: 0.5, strokeWeight: 5, }, colorScheme: innerMap!.get( 'colorScheme' ) as google.maps.ColorScheme, }) ); } void init();
JavaScript
const mapPolylines = []; const mapElement = document.querySelector('gmp-map'); let innerMap; // Initialize and add the map. async function init() { // Request the needed libraries. const [{ event }] = await Promise.all([ google.maps.importLibrary('core'), google.maps.importLibrary('maps'), ]); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Call the function after the map is loaded. event.addListenerOnce(innerMap, 'idle', () => { void getDirections(); }); } async function getDirections() { // 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.push( ...route.createPolylines({ polylineOptions: isPrimaryRoute ? { map: innerMap, strokeWeight: 5, } : { map: innerMap, strokeColor: '#669DF6', strokeOpacity: 0.5, strokeWeight: 5, }, colorScheme: innerMap.get('colorScheme'), }) ); } void init();
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>
<script>
// prettier-ignore
(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: "GOOGLE_MAPS_API_KEY"
});
</script>
</head>
<body>
<gmp-map center="37.447646, -122.113878" zoom="10"></gmp-map>
</body>
</html>अन्य रूट का अनुरोध करते समय ध्यान रखने वाली बातें
अन्य रूट का अनुरोध करते समय, इन बातों का ध्यान रखें:
- अन्य रूट का अनुरोध सिर्फ़ उन रूट के लिए किया जा सकता है जिनमें बीच में कोई वेपॉइंट न हो. अगर रूट में बीच के वेपॉइंट शामिल हैं, तब भी अन्य रूट का अनुरोध किया जा सकता है. हालांकि, ऐसा करने पर कोई गड़बड़ी नहीं होती. हालांकि, अन्य रूट नहीं दिखाए जाते.
- जवाब में ज़्यादा से ज़्यादा तीन अन्य रूट दिखाए जाते हैं. हालांकि, कभी-कभी अन्य रूट उपलब्ध नहीं होते. इसलिए, जवाब में सिर्फ़ डिफ़ॉल्ट रूट दिखाया जाता है.
- अन्य रूट की जानकारी पाने के लिए, ज़्यादा प्रोसेसिंग की ज़रूरत होती है. इसलिए, अन्य रूट का अनुरोध करने पर, अन्य रूट का अनुरोध करने पर, एपीआई के जवाब का समय बढ़ सकता है.
अन्य रूट का अनुरोध करना
अन्य रूट का अनुरोध करने के लिए, computeAlternativeRoutes को
true में 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. };
रूट पाने के लिए, रूट के कलेक्शन पर इटरेट करें. जैसे, 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); }