다음 두 가지 방법으로 <gmp-map-3d> 요소에서 경로를 계산하고 렌더링할 수 있습니다.
Route3DElement(<gmp-route-3d>)를 사용하여 선언적으로: Routes API에서 경로를 요청하고 3D 경로 다중선, 출발지 및 목적지 마커, 경로 요약 팝오버를 렌더링하는 웹 구성요소를 추가합니다.Route도우미 메서드를 사용하여 프로그래매틱 방식으로: 중간 경유지, 맞춤 필드 마스크 또는 맞춤 다중선 스타일이 필요한 경우Route.computeRoutes를 호출하고 경로를create3DPolylines,createWaypointMarkers,createPopover에 전달합니다.
두 접근 방식 모두 Maps JavaScript API의 v=beta 채널에서 사용할 수 있습니다. 베타 채널을 로드하는 방법은 버전 관리를 참고하세요.
기본 요건 및 결제
3D 경로를 표시하기 전에 Google Cloud 프로젝트를 설정하고 해당 프로젝트에 Maps JavaScript API와 Routes API를 모두 사용 설정하세요. maps3d 및 routes 라이브러리를 모두 로드합니다.
<gmp-map-3d> 렌더링은 동적 3D 지도(Immersive Maps Pro)에 따라 청구됩니다.
<gmp-route-3d> 또는 Route.computeRoutes에서 수행하는 각 경로 요청은 요청된 기능에 따라 Routes API Compute Routes SKU로 청구됩니다.
| 구성 | Routes SKU 등급 |
|---|---|
기본 경로 요청(TRAFFIC_UNAWARE 또는 WALKING, BICYCLING, TRANSIT 이동 모드, 교통정보 다중선 없음)
|
Compute Routes Essentials |
routing-preference가 traffic-aware 또는 traffic-aware-optimal로 설정되고 traffic-polylines-disabled가 사용 설정됨
|
Compute Routes Pro |
routing-preference가 traffic-aware 또는 traffic-aware-optimal로 설정되고 교통정보 색상 다중선이 사용 설정됨(교통정보 인식 환경설정이 설정된 경우 기본값)
|
Compute Routes Enterprise |
SKU 세부정보는 Maps JavaScript API 사용량 및 결제를 참고하세요.
HTML을 사용하여 3D 경로 추가하기
최소한의 코드로 출발지와 목적지 간의 경로를 표시하려면 <gmp-map-3d> 내에 <gmp-route-3d>를 중첩하고 autofits-camera를 추가하여 지도가 경로를 자동으로 프레이밍하도록 합니다.
<gmp-map-3d
style="height: 400px; width: 100%;"
mode="hybrid">
<gmp-route-3d
origin="Space Needle, Seattle, WA"
destination="Tacoma Dome, Tacoma, WA"
travel-mode="driving"
routing-preference="traffic-aware"
autofits-camera>
</gmp-route-3d>
</gmp-map-3d>
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&libraries=maps3d,routes">
</script>
YOUR_API_KEY를 Google Maps Platform API 키로 바꿉니다.
Route3DElement는 다중선 및 요약 팝오버 색상을 상위 <gmp-map-3d>의 밝은 색 구성표 또는 어두운 색 구성표에 자동으로 일치시키며 다음 속성을 지원합니다.
origin및destination:"lat,lng"좌표 문자열, 장소 리소스 이름(예:"places/ChIJ-bfVTh8VkFQRDZLQnmioK9s") 또는 주소 문자열을 허용합니다. JavaScript에서 이러한 속성은LatLng,LatLngLiteral,LatLngAltitude,LatLngAltitudeLiteral,Place객체도 허용합니다.travel-mode(travelMode):driving(기본값),walking,bicycling또는transit(멀티모달 도보 및 대중교통 노선 세그먼트 렌더링)를 허용합니다.routing-preference(routingPreference):traffic-unaware,traffic-aware또는traffic-aware-optimal를 허용합니다.traffic-polylines-disabled(trafficPolylinesDisabled): 교통정보를 반영하는 경로에서 교통량에 따른 다중선 색상 지정을 사용 중지하여 요청이 Compute Routes Enterprise 대신 Compute Routes Pro로 청구됩니다.departure-time(departureTime): HTML의 ISO 8601 타임스탬프 문자열(예:"2027-03-15T16:00:00Z") 또는 JavaScript의Date객체를 허용합니다.autofits-camera(autofitsCamera):<gmp-map-3d>표시 영역 내에서 로드된 경로를 프레이밍합니다.
경로 이벤트 처리 및 경로 데이터 읽기
Route3DElement는 경로가 렌더링을 완료하면 gmp-load를 전달하고, 경로 계산이 실패하거나 경로를 반환하지 않으면 gmp-error를 전달합니다. gmp-load가 실행되면 계산된 routes, fallbackInfo, geocodingResults 속성을 읽을 수 있습니다.
const routeElement = document.querySelector('gmp-route-3d');
routeElement.addEventListener('gmp-load', () => {
const primaryRoute = routeElement.routes?.[0];
console.log('Distance (m):', primaryRoute?.distanceMeters);
console.log('Duration:', primaryRoute?.localizedValues?.duration);
});
routeElement.addEventListener('gmp-error', () => {
console.error('Failed to load the 3D route.');
});
gmp-route-3d 대신 경로 도우미 메서드를 사용해야 하는 경우
<gmp-route-3d>는 기본 마커 및 다중선 스타일을 사용하여 단일 origin와 destination 사이의 기본 경로를 렌더링합니다. 중간 경유지, 대체 경로 선택, 커스텀 응답 필드 마스크 또는 커스텀 다중선 및 마커 스타일이 필요한 경우 3D 도우미 메서드와 함께 Route.computeRoutes를 사용하세요.
Route 클래스로 3D 경로 렌더링 맞춤설정하기
커스텀 3D 경로 워크플로의 경우 Route.computeRoutes를 호출하고 3D 도우미 메서드를 사용하여 반환된 Route 인스턴스를 <gmp-map-3d>에 렌더링합니다.
<div id="map-container" style="height: 400px; width: 100%;"></div>
<script>
async function initMap() {
const { Map3DElement, MapMode } =
await google.maps.importLibrary('maps3d');
const { Route } = await google.maps.importLibrary('routes');
const map = new Map3DElement({
mode: MapMode.HYBRID,
});
document.getElementById('map-container').append(map);
const { routes } = await Route.computeRoutes({
origin: '1800 Amphibious Blvd., Mountain View, CA 94045',
destination: 'San Francisco Ferry Building, San Francisco, CA',
travelMode: 'DRIVING',
routingPreference: 'TRAFFIC_AWARE',
extraComputations: ['TRAFFIC_ON_POLYLINE'],
fields: ['path', 'speedPaths', 'localizedValues'],
});
const route = routes?.[0];
if (!route) return;
const [polylines, markers, popover] = await Promise.all([
route.create3DPolylines({
polylineOptions: {
strokeWidth: 10,
autofitsCamera: true,
},
}),
route.createWaypointMarkers(),
route.createPopover(),
]);
map.append(...polylines, ...markers, popover);
}
</script>
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&loading=async&callback=initMap">
</script>
YOUR_API_KEY를 Google Maps Platform API 키로 바꿉니다.
호출하는 각 도우미 메서드의 ComputeRoutesRequest.fields에 필수 필드를 포함합니다.
create3DPolylines: 표준 다중선의 경우'path'또는'legs'를 요청하고,travelMode가'TRANSIT'인 경우'path'및'legs'를 요청하고, 교통량에 따라 색상이 지정된 다중선의 경우extraComputations: ['TRAFFIC_ON_POLYLINE']와 함께'speedPaths'를 요청합니다.RoutePolyline3DOptions를 전달하여polylineOptions를 맞춤설정하거나trafficPolylinesDisabled를 설정합니다.createWaypointMarkers:fields에서'path'를 요청합니다. 출발지 및 목적지 마커를 만듭니다(기본적으로Marker3DElement,CreateWaypointMarkersOptions에서markerClass로 지정된 경우MarkerElement,MarkerInteractiveElement또는Marker3DInteractiveElement). 중간 경유지는 이 메서드로 생성되지 않습니다.createPopover:'path'및'localizedValues'(대중교통 경로의 경우'legs'추가)를 요청하여 경로 중간에 요약PopoverElement를 고정합니다.