別のルートを取得する

欧州経済領域(EEA)のデベロッパー

Routes API から返されるデフォルト ルートは、通常、出発地から目的地までの最速ルートです。代替ルートをリクエストすると、API はデフォルト ルートとともに最大 3 つのルートの配列を返します。お客様は、ご自身にとって最適なルートを選択できます。

サンプル ソースコードの全文を見る

次のコードサンプルは、代替ルートをリクエストして、地図上にルートを描画する方法を示しています。

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>

サンプルを試す

代替経路をリクエストする際の考慮事項

代替ルートをリクエストする際は、次の点を考慮してください。

  • 代替ルートをリクエストできるのは、中間地点のないルートのみです。ルートで中間地点が指定されている場合に代替ルートをリクエストしても、エラーは発生しません。ただし、代替ルートは返されません。
  • レスポンスには、最大 3 つの代替ルートが含まれます。ただし、代替ルートがない場合、レスポンスにはデフォルトのルートのみが含まれます。
  • 代替ルートの計算には追加の処理が必要になるため、代替ルートをリクエストすると、API のレスポンス時間が長くなることがあります。

別の経路をリクエストする

代替ルートをリクエストするには、computeRoutes リクエストで computeAlternativeRoutestrue に設定します。

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