경로 찾기

유럽 경제 지역 (EEA) 개발자

경로는 시작 위치(출발지)와 종료 위치(목적지) 사이의 탐색 가능한 경로입니다. 도보, 자전거 또는 다양한 유형의 차량과 같은 다양한 이동 수단에 대한 경로를 가져올 수 있습니다. 거리, 경로 탐색 예상 시간, 예상 통행료, 경로 탐색을 위한 단계별 안내와 같은 경로 세부정보를 요청할 수도 있습니다.

샘플 소스 코드 전체 보기

다음 코드 샘플은 두 위치 간의 운전 경로를 가져오는 방법을 보여줍니다.

TypeScript

// Initialize and add the map.
let map: google.maps.Map;
let mapPolylines: google.maps.Polyline[] = [];
const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA

// Initialize and add the map.
async function init(): Promise<void> {
    //  Request the needed libraries.
    const [{ Map }, { Place }, { Route }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('routes'),
    ]);

    map = new Map(document.getElementById('map')!, {
        zoom: 12,
        center,
        mapTypeControl: false,
        mapId: 'DEMO_MAP_ID',
    });

    // Use address strings in a directions request.
    const requestWithAddressStrings = {
        origin: '1600 Amphitheatre Parkway, Mountain View, CA',
        destination: '345 Spear Street, San Francisco, CA',
        fields: ['path'],
    };
    console.log({ requestWithAddressStrings });

    // Use Place IDs in a directions request.
    const originPlaceInstance = new Place({
        id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA
    });

    const destinationPlaceInstance = new Place({
        id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA
    });

    const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = {
        origin: originPlaceInstance,
        destination: destinationPlaceInstance,
        fields: ['path'], // Request fields needed to draw polylines.
    };
    console.log({ requestWithPlaceIds });

    // Use lat/lng in a directions request.
    // Mountain View, CA
    const originLatLng = { lat: 37.422, lng: -122.084058 };
    // San Francisco, CA
    const destinationLatLng = { lat: 37.774929, lng: -122.419415 };

    // Define a computeRoutes request.
    const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = {
        origin: originLatLng,
        destination: destinationLatLng,
        fields: ['path'],
    };
    console.log({ requestWithLatLngs });

    // Use Plus Codes in a directions request.
    const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = {
        origin: '849VCWC8+R9', // Mountain View, CA
        destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA
        fields: ['path'],
    };
    console.log({ requestWithPlusCodes });

    // Define a routes request.
    const request: google.maps.routes.ComputeRoutesRequest = {
        origin: 'Mountain View, CA',
        destination: 'San Francisco, CA',
        travelMode: 'DRIVING',
        fields: ['path'], // Request fields needed to draw polylines.
    };

    // Call computeRoutes to get the directions.
    const { routes } = await Route.computeRoutes(request);

    // Use createPolylines to create polylines for the route.
    if (!routes) {
        console.warn('No routes found.');
        return;
    }
    mapPolylines = routes[0].createPolylines();
    // Add polylines to the map.
    mapPolylines.forEach((polyline) => {
        polyline.setMap(map);
    });

    // Create markers to start and end points.
    const markers = await routes[0].createWaypointAdvancedMarkers();
    // Add markers to the map
    markers.forEach((marker) => {
        marker.map = map;
    });

    // Display the raw JSON for the result in the console.
    console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`);

    // Fit the map to the path.
    void fitMapToPath(routes[0].path!);
}

// Helper function to fit the map to the path.
async function fitMapToPath(path: google.maps.LatLngLiteral[]) {
    const { LatLngBounds } = await google.maps.importLibrary('core');
    const bounds = new LatLngBounds();
    path.forEach((point) => {
        bounds.extend(point);
    });
    map.fitBounds(bounds);
}

void init();

JavaScript

// Initialize and add the map.
let map;
let mapPolylines = [];
const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA

// Initialize and add the map.
async function init() {
    //  Request the needed libraries.
    const [{ Map }, { Place }, { Route }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('routes'),
    ]);

    map = new Map(document.getElementById('map'), {
        zoom: 12,
        center,
        mapTypeControl: false,
        mapId: 'DEMO_MAP_ID',
    });

    // Use address strings in a directions request.
    const requestWithAddressStrings = {
        origin: '1600 Amphitheatre Parkway, Mountain View, CA',
        destination: '345 Spear Street, San Francisco, CA',
        fields: ['path'],
    };
    console.log({ requestWithAddressStrings });

    // Use Place IDs in a directions request.
    const originPlaceInstance = new Place({
        id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA
    });

    const destinationPlaceInstance = new Place({
        id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA
    });

    const requestWithPlaceIds = {
        origin: originPlaceInstance,
        destination: destinationPlaceInstance,
        fields: ['path'], // Request fields needed to draw polylines.
    };
    console.log({ requestWithPlaceIds });

    // Use lat/lng in a directions request.
    // Mountain View, CA
    const originLatLng = { lat: 37.422, lng: -122.084058 };
    // San Francisco, CA
    const destinationLatLng = { lat: 37.774929, lng: -122.419415 };

    // Define a computeRoutes request.
    const requestWithLatLngs = {
        origin: originLatLng,
        destination: destinationLatLng,
        fields: ['path'],
    };
    console.log({ requestWithLatLngs });

    // Use Plus Codes in a directions request.
    const requestWithPlusCodes = {
        origin: '849VCWC8+R9', // Mountain View, CA
        destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA
        fields: ['path'],
    };
    console.log({ requestWithPlusCodes });

    // Define a routes request.
    const request = {
        origin: 'Mountain View, CA',
        destination: 'San Francisco, CA',
        travelMode: 'DRIVING',
        fields: ['path'], // Request fields needed to draw polylines.
    };

    // Call computeRoutes to get the directions.
    const { routes } = await Route.computeRoutes(request);

    // Use createPolylines to create polylines for the route.
    if (!routes) {
        console.warn('No routes found.');
        return;
    }
    mapPolylines = routes[0].createPolylines();
    // Add polylines to the map.
    mapPolylines.forEach((polyline) => {
        polyline.setMap(map);
    });

    // Create markers to start and end points.
    const markers = await routes[0].createWaypointAdvancedMarkers();
    // Add markers to the map
    markers.forEach((marker) => {
        marker.map = map;
    });

    // Display the raw JSON for the result in the console.
    console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`);

    // Fit the map to the path.
    void fitMapToPath(routes[0].path);
}

// Helper function to fit the map to the path.
async function fitMapToPath(path) {
    const { LatLngBounds } = await google.maps.importLibrary('core');
    const bounds = new LatLngBounds();
    path.forEach((point) => {
        bounds.extend(point);
    });
    map.fitBounds(bounds);
}

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>
        <div id="map"></div>
    </body>
</html>

computeRoutes() 메서드를 호출하여 두 위치 간의 경로를 요청합니다. 다음 예에서는 요청을 정의한 후 computeRoutes()를 호출하여 경로를 가져오는 방법을 보여줍니다. computeRoutes()는 Route 클래스의 정적 메서드이므로 Route.computeRoutes(request)를 직접 호출합니다. 또한 요청은 fields 속성을 응답 필드 마스크로 설정해야 합니다.

  // Import the Routes library.
  const { Route } = await google.maps.importLibrary('routes');

  // Define a computeRoutes request.
  const request = {
    origin: 'Mountain View, CA',
    destination: 'San Francisco, CA',
    fields: ['path'], // Required: response field mask.
  };

  // Call the computeRoutes() method to get routes.
  const {routes} = await Route.computeRoutes(request);
    

지도에 경로를 그리려면 path 필드로 요청한 경로에서 createPolylines()를 호출합니다. 지도에 다중선 표시를 참고하세요.

반환할 필드 선택

경로를 요청할 때는 필드 마스크를 사용하여 응답에서 반환할 정보를 지정해야 합니다. 필드 마스크에서 경로 클래스 속성의 이름을 지정할 수 있습니다.

필드 마스크를 사용하면 불필요한 데이터를 요청하지 않으므로 응답 지연 시간이 줄어들고 시스템에 필요하지 않은 정보가 반환되지 않습니다.

다음 스니펫과 같이 ComputeRoutesRequest.fields 속성을 설정하여 필요한 필드 목록을 지정합니다.

TypeScript

// Define a routes request.
const request: google.maps.routes.ComputeRoutesRequest = {
    origin: 'Mountain View, CA',
    destination: 'San Francisco, CA',
    travelMode: 'DRIVING',
    fields: ['path'], // Request fields needed to draw polylines.
};

JavaScript

// Define a routes request.
const request = {
    origin: 'Mountain View, CA',
    destination: 'San Francisco, CA',
    travelMode: 'DRIVING',
    fields: ['path'], // Request fields needed to draw polylines.
};

경로의 위치 지정

경로를 계산하려면 최소한 경로 출발지와 경로 목적지의 위치, 필드 마스크를 지정해야 합니다. 경로를 따라 중간 경유지를 지정하고 경유지를 사용하여 경로를 따라 정류장 또는 통과 지점을 추가하는 등의 다른 작업을 수행할 수도 있습니다.

ComputeRoutesRequest에서 다음 방법 중 하나로 위치를 지정할 수 있습니다.

요청에서 모든 경유지의 위치를 동일한 방식으로 지정하거나 혼합할 수 있습니다. 예를 들어 출발지 경유지에는 위도/경도 좌표를 사용하고 목적지 경유지에는 Place 객체를 사용할 수 있습니다.

효율성과 정확성을 위해 위도/경도 좌표나 주소 문자열 대신 Place 객체를 사용하세요. 장소 ID는 고유하게 명시적이며 액세스 포인트 및 교통 변수와 같은 경로를 위한 지오코딩 이점을 제공합니다. 이러한 함수는 다른 방식으로 위치를 지정할 때 발생할 수 있는 다음과 같은 상황을 방지하는 데 도움이 됩니다.

  • 위도/경도 좌표를 사용하면 해당 좌표에 가장 가까운 도로에 위치가 스냅될 수 있습니다. 이 도로는 숙박 시설의 액세스 포인트가 아니거나 목적지로 빠르고 안전하게 이어지는 도로가 아닐 수 있습니다.
  • 주소 문자열은 경로를 계산하기 전에 먼저 Routes API에서 지오코딩하여 위도/경도 좌표로 변환해야 합니다. 이 변환은 성능에 영향을 미칠 수 있습니다.

위치를 Place 객체로 지정(권장)

장소를 사용하여 위치를 지정하려면 새 Place 인스턴스를 만듭니다. 다음 스니펫은 origin 및 destination의 새 Place 인스턴스를 만든 다음 ComputeRoutesRequest에서 사용하는 방법을 보여줍니다.

TypeScript

// Use Place IDs in a directions request.
const originPlaceInstance = new Place({
    id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA
});

const destinationPlaceInstance = new Place({
    id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA
});

const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = {
    origin: originPlaceInstance,
    destination: destinationPlaceInstance,
    fields: ['path'], // Request fields needed to draw polylines.
};

JavaScript

// Use Place IDs in a directions request.
const originPlaceInstance = new Place({
    id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA
});

const destinationPlaceInstance = new Place({
    id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA
});

const requestWithPlaceIds = {
    origin: originPlaceInstance,
    destination: destinationPlaceInstance,
    fields: ['path'], // Request fields needed to draw polylines.
};

위도/경도 좌표

위치를 위도/경도 좌표로 지정하려면 새 google.maps.LatLngLiteral, google.maps.LatLngAltitude 또는 google.maps.LatLngAltitudeLiteral 인스턴스를 만듭니다. 다음 스니펫은 origin 및 destination의 새 google.maps.LatLngLiteral 인스턴스를 만든 다음 computeRoutesRequest에서 사용하는 방법을 보여줍니다.

TypeScript

// Use lat/lng in a directions request.
// Mountain View, CA
const originLatLng = { lat: 37.422, lng: -122.084058 };
// San Francisco, CA
const destinationLatLng = { lat: 37.774929, lng: -122.419415 };

// Define a computeRoutes request.
const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = {
    origin: originLatLng,
    destination: destinationLatLng,
    fields: ['path'],
};

JavaScript

// Use lat/lng in a directions request.
// Mountain View, CA
const originLatLng = { lat: 37.422, lng: -122.084058 };
// San Francisco, CA
const destinationLatLng = { lat: 37.774929, lng: -122.419415 };

// Define a computeRoutes request.
const requestWithLatLngs = {
    origin: originLatLng,
    destination: destinationLatLng,
    fields: ['path'],
};

주소 문자열

주소 문자열은 문자열로 표현되는 리터럴 주소입니다(예: '1600 Amphitheatre Parkway, Mountain View, CA'). 지오코딩은 주소 문자열을 위도 및 경도 좌표(예: 위도 37.423021 및 경도 -122.083739)로 변환하는 프로세스입니다.

주소 문자열을 경유지의 위치로 전달하면 경로 라이브러리가 내부적으로 문자열을 지오코딩하여 위도 및 경도 좌표로 변환합니다.

다음 스니펫은 origin 및 destination의 주소 문자열을 사용하여 ComputeRoutesRequest를 만드는 방법을 보여줍니다.

TypeScript

// Use address strings in a directions request.
const requestWithAddressStrings = {
    origin: '1600 Amphitheatre Parkway, Mountain View, CA',
    destination: '345 Spear Street, San Francisco, CA',
    fields: ['path'],
};

JavaScript

// Use address strings in a directions request.
const requestWithAddressStrings = {
    origin: '1600 Amphitheatre Parkway, Mountain View, CA',
    destination: '345 Spear Street, San Francisco, CA',
    fields: ['path'],
};

주소의 리전을 설정합니다.

불완전한 주소 문자열을 경유지의 위치로 전달하면 API가 잘못된 지오코딩된 위도/경도 좌표를 사용할 수 있습니다. 예를 들어 운전 경로의 출발지로 'Toledo'를, 목적지로 'Madrid'를 지정하여 요청합니다.

// Define a request with an incomplete address string.
const request = {
  origin: 'Toledo',
  destination: 'Madrid',
};
    

이 예에서 'Toledo'는 스페인이 아닌 미국 오하이오주의 도시로 해석됩니다. 따라서 요청은 빈 배열을 반환하며, 이는 경로가 없음을 의미합니다.

regionCode 매개변수를 포함하여 특정 지역에 편중된 결과를 반환하도록 API를 구성할 수 있습니다. 이 매개변수는 지역 코드를 ccTLD('최상위 도메인') 2자리 값으로 지정합니다. 대부분의 ccTLD 코드는 ISO 3166-1 코드와 동일하지만 일부 주목할 만한 예외가 있습니다. 예를 들어 영국의 ccTLD는 'uk'(.co.uk)이지만 ISO 3166-1 코드는 'gb'입니다(엄밀히 말하면 '영국' 항목).

regionCode 매개변수를 포함하는 'Toledo'에서 'Madrid'로의 경로 요청은 'Toledo'가 스페인의 도시로 해석되므로 적절한 결과를 반환합니다.

const request = {
  origin: 'Toledo',
  destination: 'Madrid',
  region: 'es', // Specify the region code for Spain.
};
    

Plus Code

많은 사람이 정확한 주소를 가지고 있지 않기 때문에 배송을 받기 어려울 수 있습니다. 또는 주소가 있는 사용자가 뒷문이나 하역장과 같은 더 구체적인 위치에서 배송을 받기를 원할 수도 있습니다.

Plus Code는 실제 주소가 없는 사람이나 장소의 상세 주소와 같습니다. Plus Code는 도로명과 번호가 있는 주소 대신 위도/경도 좌표를 기반으로 하며 숫자와 문자로 표시됩니다.

Google은 모든 사람과 사물에 주소의 이점을 제공하기 위해 Plus Code를 개발했습니다. Plus Code는 위도/경도 좌표에서 파생된 인코딩된 위치 참조로, 1/8000도x1/8000도(적도에서 14mx14m) 이하의 영역을 나타냅니다. Plus Code는 상세 주소가 없거나 건물에 번호가 지정되지 않거나 거리 이름이 없는 장소의 상세 주소 대신 사용할 수 있습니다.

Plus Code는 글로벌 코드 또는 복합 코드로 형식이 지정되어야 합니다.

  • 글로벌 코드는 4자리 지역 번호와 6자 이상의 로컬 코드로 구성됩니다. 예를 들어 '1600 Amphitheatre Parkway, Mountain View, CA' 주소의 경우 글로벌 코드는 '849V'이고 지역 코드는 'CWC8+R9'입니다. 그런 다음 10자리의 Plus Code 전체를 사용하여 위치 값을 '849VCWC8+R9'로 지정합니다.
  • 복합 코드는 6자 이상의 로컬 코드와 명시적인 위치로 구성됩니다. 예를 들어 '450 Serra Mall, Stanford, CA 94305, USA' 주소의 지역 코드는 'CRHJ+C3'입니다. 복합 주소의 경우 지역 코드와 주소의 시, 주, 우편번호, 국가 부분을 'CRHJ+C3 Stanford, CA 94305, USA' 형식으로 결합합니다.

다음 스니펫은 Plus Code를 사용하여 경로 출발지와 목적지의 경유지를 지정하여 경로를 계산하는 방법을 보여줍니다.

TypeScript

// Use Plus Codes in a directions request.
const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = {
    origin: '849VCWC8+R9', // Mountain View, CA
    destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA
    fields: ['path'],
};

JavaScript

// Use Plus Codes in a directions request.
const requestWithPlusCodes = {
    origin: '849VCWC8+R9', // Mountain View, CA
    destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA
    fields: ['path'],
};