বিকল্প রুট পান

ইউরোপীয় অর্থনৈতিক অঞ্চল (EEA) ডেভেলপাররা

Routes API দ্বারা ফেরত দেওয়া ডিফল্ট রুটটি সাধারণত উৎপত্তিস্থল থেকে গন্তব্যস্থলে পৌঁছানোর দ্রুততম রুট। যখন আপনি বিকল্প রুটের অনুরোধ করেন, তখন API ডিফল্ট রুটের সাথে সর্বাধিক তিনটি রুটের একটি অ্যারে ফেরত দেয়। এরপর আপনার গ্রাহকরা তাদের জন্য সবচেয়ে উপযুক্ত রুট বেছে নিতে পারেন।

সম্পূর্ণ উদাহরণ সোর্স কোডটি দেখুন

নিম্নলিখিত কোড নমুনাটি দেখায় কিভাবে বিকল্প রুটগুলির জন্য অনুরোধ করতে হয় এবং তারপর একটি মানচিত্রে রুটগুলি আঁকতে হয়।

টাইপস্ক্রিপ্ট

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();

জাভাস্ক্রিপ্ট

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();

সিএসএস

/*
 * 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>
  <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>

নমুনা চেষ্টা করুন

বিকল্প রুটের অনুরোধ করার সময় বিবেচনার বিষয়গুলি

বিকল্প রুটের অনুরোধ করার সময়, নিম্নলিখিত বিষয়গুলি বিবেচনা করুন:

  • আপনি শুধুমাত্র মধ্যবর্তী ওয়েপয়েন্ট ছাড়া রুটের জন্য বিকল্প রুটের অনুরোধ করতে পারেন। রুট মধ্যবর্তী ওয়েপয়েন্ট নির্দিষ্ট করে দিলে বিকল্প রুটের অনুরোধ করলে কোনও ত্রুটি হয় না। তবে, কোনও বিকল্প রুট ফেরত দেওয়া হয় না।
  • প্রতিক্রিয়াটিতে সর্বাধিক তিনটি বিকল্প রুট থাকে। তবে, কখনও কখনও কোনও বিকল্প রুট পাওয়া যায় না তাই প্রতিক্রিয়াটিতে কেবল ডিফল্ট রুট থাকে।
  • বিকল্প রুট গণনা করার জন্য অতিরিক্ত প্রক্রিয়াকরণের প্রয়োজন হওয়ায়, বিকল্প রুট অনুরোধ করলে API-এর প্রতিক্রিয়া সময় বাড়তে পারে।

বিকল্প রুটের অনুরোধ করুন

বিকল্প রুট অনুরোধ করতে, computeRoutes অনুরোধে computeAlternativeRoutes true তে সেট করুন।

// 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.
};

রুটগুলি পেতে, routes অ্যারের মাধ্যমে পুনরাবৃত্তি করুন (উদাহরণস্বরূপ, 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);
}