경로 행렬은 경로 정보의 2차원 배열로, 행은 출발지에 해당하고 열은 목적지에 해당합니다. 출발지 및 목적지 목록이 주어지면 경로 행렬 클래스는 각 출발지에서 시작하여 각 목적지에서 끝나는 경로의 거리와 시간을 계산합니다. 경로 행렬 클래스를 사용하여 여러 출발지 및 목적지의 경로 거리와 시간을 계산합니다.
샘플 소스 코드 전체 보기
이 예에서는 경로 행렬 클래스를 사용하여 여러 출발지와 목적지 간의 이동 거리와 시간을 계산하는 방법을 보여줍니다.
TypeScript
// Initialize and add the map. let map: google.maps.Map; const markers: google.maps.marker.AdvancedMarkerElement[] = []; const center = { lat: 51.55, lng: -1.8 }; async function init(): Promise<void> { // Request the needed libraries. const [ { Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }, { LatLngBounds, UnitSystem }, ] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('marker'), google.maps.importLibrary('routes'), google.maps.importLibrary('core'), ]); const bounds = new LatLngBounds(); map = new Map(document.getElementById('map')!, { zoom: 8, center, mapId: 'DEMO_MAP_ID', }); // Build the request using Place instances. const origin1 = new Place({ id: 'ChIJ83WZp86p2EcRbMrkYqGncBQ', // Greenwich, London, UK }); const origin2 = new Place({ id: 'ChIJCSkVvleJc0gR8HHaTGpajKc', // Southampton, UK }); const destinationA = new Place({ id: 'ChIJYdizgWaDcUgRH9eaSy6y5I4', // Bristol, UK }); const destinationB = new Place({ id: 'ChIJ9VPsNNQCbkgRDmeGZdsGNBQ', // Cardiff, UK }); await Promise.all([ origin1.fetchFields({ fields: ['location', 'displayName'] }), origin2.fetchFields({ fields: ['location', 'displayName'] }), destinationA.fetchFields({ fields: ['location', 'displayName'] }), destinationB.fetchFields({ fields: ['location', 'displayName'] }), ]); const destinations = [destinationA, destinationB]; const origins = [origin1, origin2]; const request: google.maps.routes.ComputeRouteMatrixRequest = { origins, destinations, travelMode: 'DRIVING', units: UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], }; // Show the request. document.getElementById('request')!.innerText = JSON.stringify( request, null, 2 ); // Get the RouteMatrix response. const response = await RouteMatrix.computeRouteMatrix(request); // Show the response. document.getElementById('response')!.innerText = JSON.stringify( response, null, 2 ); // Add markers for the origins. for (const origin of origins) { if (origin.location) { const pin = new PinElement({ glyphText: 'O', glyphColor: 'white', background: '#137333', borderColor: 'white', }); const marker = new AdvancedMarkerElement({ map, position: origin.location, title: `Origin: ${origin.displayName}`, }); marker.append(pin); markers.push(marker); bounds.extend(origin.location); } } // Add markers for the destinations. for (const destination of destinations) { if (destination.location) { const pin = new PinElement({ glyphText: 'D', glyphColor: 'white', background: '#C5221F', borderColor: 'white', }); const marker = new AdvancedMarkerElement({ map, position: destination.location, content: pin, title: `Destination: ${destination.displayName ?? 'Unknown'}`, }); markers.push(marker); bounds.extend(destination.location); } } // Fit the map to the bounds of all markers. map.fitBounds(bounds); } void init();
JavaScript
// Initialize and add the map. let map; const markers = []; const center = { lat: 51.55, lng: -1.8 }; async function init() { // Request the needed libraries. const [ { Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }, { LatLngBounds, UnitSystem }, ] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('marker'), google.maps.importLibrary('routes'), google.maps.importLibrary('core'), ]); const bounds = new LatLngBounds(); map = new Map(document.getElementById('map'), { zoom: 8, center, mapId: 'DEMO_MAP_ID', }); // Build the request using Place instances. const origin1 = new Place({ id: 'ChIJ83WZp86p2EcRbMrkYqGncBQ', // Greenwich, London, UK }); const origin2 = new Place({ id: 'ChIJCSkVvleJc0gR8HHaTGpajKc', // Southampton, UK }); const destinationA = new Place({ id: 'ChIJYdizgWaDcUgRH9eaSy6y5I4', // Bristol, UK }); const destinationB = new Place({ id: 'ChIJ9VPsNNQCbkgRDmeGZdsGNBQ', // Cardiff, UK }); await Promise.all([ origin1.fetchFields({ fields: ['location', 'displayName'] }), origin2.fetchFields({ fields: ['location', 'displayName'] }), destinationA.fetchFields({ fields: ['location', 'displayName'] }), destinationB.fetchFields({ fields: ['location', 'displayName'] }), ]); const destinations = [destinationA, destinationB]; const origins = [origin1, origin2]; const request = { origins, destinations, travelMode: 'DRIVING', units: UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], }; // Show the request. document.getElementById('request').innerText = JSON.stringify( request, null, 2 ); // Get the RouteMatrix response. const response = await RouteMatrix.computeRouteMatrix(request); // Show the response. document.getElementById('response').innerText = JSON.stringify( response, null, 2 ); // Add markers for the origins. for (const origin of origins) { if (origin.location) { const pin = new PinElement({ glyphText: 'O', glyphColor: 'white', background: '#137333', borderColor: 'white', }); const marker = new AdvancedMarkerElement({ map, position: origin.location, title: `Origin: ${origin.displayName}`, }); marker.append(pin); markers.push(marker); bounds.extend(origin.location); } } // Add markers for the destinations. for (const destination of destinations) { if (destination.location) { const pin = new PinElement({ glyphText: 'D', glyphColor: 'white', background: '#C5221F', borderColor: 'white', }); const marker = new AdvancedMarkerElement({ map, position: destination.location, content: pin, title: `Destination: ${destination.displayName ?? 'Unknown'}`, }); markers.push(marker); bounds.extend(destination.location); } } // Fit the map to the bounds of all markers. map.fitBounds(bounds); } void init();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #container { height: 100%; display: flex; } #sidebar { flex-basis: 15rem; flex-grow: 1; padding: 1rem; max-width: 30rem; height: 100%; box-sizing: border-box; overflow: auto; } #map { flex-basis: 0; flex-grow: 4; height: 100%; } #sidebar { flex-direction: column; }
HTML
<html>
<head>
<title>Route matrix</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="container">
<div id="map"></div>
<div id="sidebar">
<h3 style="flex-grow: 0">Request</h3>
<pre style="flex-grow: 1" id="request"></pre>
<h3 style="flex-grow: 0">Response</h3>
<pre style="flex-grow: 1" id="response"></pre>
</div>
</div>
</body>
</html>요청 한도
The computeRouteMatrix 메서드는 주소 또는 장소 인스턴스를 사용하는 경유지 및 항목에 대해 다음과 같은 요청
한도를 적용합니다. 항목은 경로 행렬의 각 출발지와 목적지 간의 경로
이므로 항목 수는 출발지 수에 목적지 수
를 곱한 값입니다. 예를 들어 출발지가 10개이고 목적지가 10
개인 경우 항목은 100개입니다.
- 항목 수는
TRANSIT경로가 아닌 경로의 경우 625개를 초과할 수 없습니다. TRANSIT경로를 지정하는 경우 항목 수는 100개를 초과할 수 없습니다.TRAFFIC_AWARE_OPTIMAL을 지정하는 경우 항목 수는 100개를 초과할 수 없습니다.- 주소 또는 장소 인스턴스를 사용하여 출발지 또는 목적지를 지정하는 경우 이 방법으로 총 50개까지 지정할 수 있습니다.
자세한 내용은 대중교통 경로 가져오기를 참고하세요.
경로 행렬 요청 예시
다음 예에서는 ComputeRouteMatrixRequest를 보여줍니다. 이 예에서는
다음 작업을 실행합니다.
- 출발지 경유지 2개와 목적지 경유지 2개의 배열을 지정하는 방법을 보여줍니다. 이 메서드는 각 출발지에서 각 목적지까지의 경로를 계산하므로 응답에는 4개의 경로가 포함됩니다.
배열에서 첫 번째 요소는 색인 0에 있고 두 번째 요소는 색인 1에 있습니다. - 반환할 필드를 지정합니다. 이 예에서는 각 경로에 대해
durationMillis,distanceMeters,condition을 반환하도록 요청이 구성됩니다.
TypeScript
const destinations = [destinationA, destinationB]; const origins = [origin1, origin2]; const request: google.maps.routes.ComputeRouteMatrixRequest = { origins, destinations, travelMode: 'DRIVING', units: UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], };
JavaScript
const destinations = [destinationA, destinationB]; const origins = [origin1, origin2]; const request = { origins, destinations, travelMode: 'DRIVING', units: UnitSystem.METRIC, fields: ['distanceMeters', 'durationMillis', 'condition'], };
다음 예와 같이 응답에는 모든 출발지 및 목적지 경유지의 조합에 대한 4가지 가능한 경로가 포함됩니다.
"matrix": { "rows": [ { "items": [ { "condition": "ROUTE_EXISTS", "distanceMeters": 202587, "durationMillis": 10040000 }, { "condition": "ROUTE_EXISTS", "distanceMeters": 252734, "durationMillis": 12240000 } ] }, { "items": [ { "condition": "ROUTE_EXISTS", "distanceMeters": 166135, "durationMillis": 6596000 }, { "condition": "ROUTE_EXISTS", "distanceMeters": 216282, "durationMillis": 8797000 } ] } ] }
출발지 및 목적지 색인을 사용하여 2차원 배열에서 해당하는
RouteMatrixItem을 찾아 결과에서 각 경로를 식별합니다. 예를 들어 요청에서 색인 1의 출발지와
목적지 0에서 계산된 경로를 설명하는RouteMatrixItem 은 RouteMatrix.rows
배열의 두 번째 요소와 RouteMatrixRow.items 배열의 첫 번째 요소에 있습니다.
다음 코드 스니펫은 특정 출발지 및 목적지의 경로를 찾기 위해 RouteMatrixItem을 식별하는 방법을 보여줍니다.
// Find the route for origin 'x' and destination 'y'. const {matrix} = await RouteMatrix.computeRouteMatrix(request); const myRouteMatrixItem = matrix.rows[x].items[y];
반환할 필드 선택
경로 행렬을 요청할 때는 필드 마스크를 사용하여 응답에서 반환해야 하는 정보를 지정해야 합니다.
필드 마스크를 사용하면 불필요한 데이터를 요청하지 않으므로 응답 지연 시간을 줄이고 시스템에 필요하지 않은 정보가 반환되지 않도록 할 수 있습니다.
다음 스니펫과 같이
ComputeRoutesMatrixRequest.fields 속성을 설정하여 필요한 필드 목록을 지정합니다.
fields: ['durationMillis', 'distanceMeters', 'condition'],
사용할 필드 마스크 결정
다음과 같은 방법으로 사용할 필드를 결정하고 필드 마스크를 구성할 수 있습니다.
['*']필드 마스크를 사용하여 모든 필드를 요청 합니다.- 원하는 필드의
RouteMatrixItem클래스에서 필드의 계층 구조를 확인합니다. 필드 마스크를 구성하려면 이 형식을 사용하여 이전 단계에 표시된 필드의 계층 구조를 사용합니다.
topLevelField[.secondLevelField][.thirdLevelField][...]
예를 들어 이 RouteMatrixItem의 경우
"travelAdvisory": { "fuelConsumptionMicroliters": 0, "tollInfo": { "estimatedPrices": [ { "currencyCode": "USD", "units": 4, "nanos": 400000000 } ] } },
RouteMatrixItem의 tollInfo 필드만 반환하려면 필드 마스크는 다음과 같습니다.
fields: ['travelAdvisory.tollInfo']
대신 예상 연료 소비량을 요청하려면 필드 마스크는 다음과 같습니다.
fields: ['travelAdvisory.fuelConsumptionMicroliters']
둘 다 요청하려면 필드 마스크는 다음과 같습니다.
fields: ['travelAdvisory.fuelConsumptionMicroliters', 'travelAdvisory.tollInfo']
전체 여행 권고 사항을 요청하려면 필드 마스크는 다음과 같습니다.
fields: ['travelAdvisory']
대중교통 경로 행렬 요청
해당 지역에서 사용할 수 있는 대중교통 옵션을 사용하는 대중교통 경로 행렬을 가져옵니다. 대중교통 옵션에는 버스, 지하철, 기차 등이 포함될 수 있습니다. 대중교통 경로 행렬을 요청하려면 다음 단계를 따르세요.
travelMode를TRANSIT으로 설정합니다.travelAdvisory필드를 요청합니다.
대중교통 경로에 대해 자세히 알아보세요.