대체 경로 가져오기

유럽 경제 지역 (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);
}