WebGL 오버레이 뷰를 사용하면 WebGL을 직접 사용하거나 Three.js와 같은 인기 그래픽 라이브러리를 사용하여 지도에 콘텐츠를 추가할 수 있습니다. WebGL 오버레이 뷰를 사용하면 Google Maps Platform에서 벡터 기본 지도를 렌더링하는 데 사용하는 동일한 WebGL 렌더링 컨텍스트에 직접 액세스할 수 있습니다. 이와 같이 공유된 렌더링 컨텍스트를 사용하면 3D 빌딩 도형의 깊이 오클루전 및 2D/3D 콘텐츠를 기본 지도 렌더링과 동기화할 수 있는 기능과 같은 이점이 있습니다. WebGL 오버레이 뷰로 렌더링된 객체는 위도/경도 좌표에 연결할 수도 있으며, 그러면 지도에서 드래그, 확대/축소, 화면 이동하거나 기울일 때 객체가 그에 따라 움직입니다.
요구사항
WebGL 오버레이 뷰를 사용하려면 벡터 지도를 사용 설정한 상태에서 지도 ID를 사용하여 지도를 로드해야 합니다. 완전한 3D 카메라 관리가 가능하도록 지도 ID를 만들 때 기울기 및 회전을 사용 설정하는 것이 좋습니다.
자세한 내용은 개요를 참고하세요.
WebGL 오버레이 뷰 추가
지도에 오버레이를 추가하려면 google.maps.WebGLOverlayView를 구현한 다음 setMap을 사용하여 지도 인스턴스에 전달하세요.
// Create a map instance.constmap=newgoogle.maps.Map(mapDiv,mapOptions);// Create a WebGL Overlay View instance.constwebglOverlayView=newgoogle.maps.WebGLOverlayView();// Add the overlay to the map.webglOverlayView.setMap(map);
수명 주기 후크
WebGL 오버레이 뷰는 벡터 기본 지도의 WebGL 렌더링 컨텍스트의 수명 주기에서 여러 시점에 호출되는 후크 집합을 제공합니다. 이러한 수명 주기 후크를 통해 오버레이에서 렌더링하려는 모든 항목을 설정하고, 그리고, 해체합니다.
onAdd()는 오버레이가 생성될 때 호출됩니다. 이를 사용하여 오버레이가 그려지기 전에 WebGL 렌더링 컨텍스트에 즉시 액세스할 필요가 없는 중간 데이터 구조를 가져오거나 만들 수 있습니다.
렌더링 컨텍스트를 사용할 수 있게 되면 onContextRestored({gl})가 호출됩니다. 이를 사용하여 셰이더, GL 버퍼 객체 등의 WebGL 상태를 초기화하거나 바인딩할 수 있습니다. onContextRestored()는 필드가 하나인 WebGLStateOptions 인스턴스를 사용합니다.
gl은 기본 지도에서 사용하는 WebGLRenderingContext의 핸들입니다.
onDraw({gl, transformer})는 기본 지도에 장면을 렌더링합니다.
onDraw()의 매개변수는 다음 두 필드가 포함된 WebGLDrawOptions 객체입니다.
gl은 기본 지도에서 사용하는 WebGLRenderingContext의 핸들입니다.
transformer는 지도 좌표에서 모델 뷰 투영 행렬로 변환하는 도우미 함수를 제공하며, 이를 사용하여 지도 좌표를 세계 공간, 카메라 공간, 화면 공간으로 변환할 수 있습니다.
onContextLost()는 어떤 이유로든 렌더링 컨텍스트가 손실될 때 호출되며 기존 GL 상태는 더 이상 필요하지 않으므로 여기에서 삭제해야 합니다.
onStateUpdate({gl})는 렌더링 루프 외부의 GL 상태를 업데이트하고 requestStateUpdate가 호출될 때 호출되며, 필드가 하나인 WebGLStateOptions 인스턴스를 사용합니다.
gl은 기본 지도에서 사용하는 WebGLRenderingContext의 핸들입니다.
onRemove()는 오버레이가 WebGLOverlayView.setMap(null)을 사용하여 지도에서 삭제될 때 호출되며 여기에서 모든 중간 객체를 삭제해야 합니다.
다음 예에서는 모든 수명 주기 후크가 기본적으로 구현됩니다.
constwebglOverlayView=newgoogle.maps.WebGLOverlayView();webglOverlayView.onAdd=()=>{// Do setup that does not require access to rendering context.}webglOverlayView.onContextRestored=({gl})=>{// Do setup that requires access to rendering context before onDraw call.}webglOverlayView.onStateUpdate=({gl})=>{// Do GL state setup or updates outside of the render loop.}webglOverlayView.onDraw=({gl,transformer})=>{// Render objects.}webglOverlayView.onContextLost=()=>{// Clean up pre-existing GL state.}webglOverlayView.onRemove=()=>{// Remove all intermediate objects.}webglOverlayView.setMap(map);
GL 상태 재설정
WebGL 오버레이 뷰는 기본 지도의 WebGL 렌더링 컨텍스트를 노출합니다. 따라서 객체 렌더링을 완료하면 GL 상태를 원래 상태로 재설정하는 것이 매우 중요합니다. GL 상태를 재설정하지 않으면 GL 상태 충돌이 발생하여 지도와 지정한 객체가 모두 렌더링되지 않을 수도 있습니다.
GL 상태 재설정은 일반적으로 onDraw() 후크에서 처리됩니다. 예를 들어 Three.js는 GL 상태의 변경사항을 지우는 도우미 함수를 제공합니다.
webglOverlayView.onDraw=({gl,transformer})=>{// Specify an object to render.renderer.render(scene,camera);renderer.resetState();}
지도 또는 객체가 렌더링되지 않으면 GL 상태가 재설정되지 않았을 가능성이 매우 큽니다.
좌표 변환
벡터 지도에서 객체의 위치는 위도 및 경도 좌표와 고도의 조합을 제공하여 지정됩니다. 하지만 3D 그래픽은 세계 공간, 카메라 공간 또는 화면 공간에서 지정됩니다.
지도 좌표를 이렇게 흔히 사용되는 공간으로 쉽게 변환할 수 있도록 WebGL 오버레이 뷰는 onDraw() 후크에 다음을 가져와 Float64Array를 반환하는 coordinateTransformer.fromLatLngAltitude(latLngAltitude, rotationArr,
scalarArr) 도우미 함수를 제공합니다.
latLngAltitude: 위도/경도/고도 좌표(LatLngAltitude 또는 LatLngAltitudeLiteral)
rotationArr: 도 단위로 지정된 오일러 회전 각도의 Float32Array
scalarArr: 기본 축에 적용할 스칼라의 Float32Array
다음 예에서는 fromLatLngAltitude()를 사용하여 Three.js에서 카메라 투영 행렬을 만듭니다.
다음은 인기 있는 오픈소스 WebGL 라이브러리 Three.js를 사용하여 지도에 3D 객체를 배치하는 간단한 예입니다. WebGL 오버레이 뷰를 사용하여 이 페이지의 상단에서 실행되는 예를 빌드하는 방법을 자세히 알아보려면 WebGL 가속 지도 환경 Codelab 빌드를 참고하세요.
constwebglOverlayView=newgoogle.maps.WebGLOverlayView();letscene,renderer,camera,loader;webglOverlayView.onAdd=()=>{// Set up the Three.js scene.scene=newTHREE.Scene();camera=newTHREE.PerspectiveCamera();constambientLight=newTHREE.AmbientLight(0xffffff,0.75);// Soft white light.scene.add(ambientLight);// Load the 3D model with GLTF Loader from Three.js.loader=newGLTFLoader();loader.load("pin.gltf");}webglOverlayView.onContextRestored=({gl})=>{// Create the Three.js renderer, using the// maps's WebGL rendering context.renderer=newTHREE.WebGLRenderer({canvas:gl.canvas,context:gl,...gl.getContextAttributes(),});renderer.autoClear=false;}webglOverlayView.onDraw=({gl,transformer})=>{// Update camera matrix to ensure the model is georeferenced correctly on the map.constmatrix=transformer.fromLatLngAltitude({lat:mapOptions.center.lat,lng:mapOptions.center.lng,altitude:120,});camera.projectionMatrix=newTHREE.Matrix4().fromArray(matrix);// Request a redraw and render the scene.webglOverlayView.requestRedraw();renderer.render(scene,camera);// Always reset the GL state.renderer.resetState();}// Add the overlay to the map.webglOverlayView.setMap(map);
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eWebGL Overlay View empowers you to seamlessly integrate 3D and 2D content into Google Maps using WebGL directly or via libraries like Three.js, leveraging the same rendering context for synchronized visuals and depth occlusion with buildings.\u003c/p\u003e\n"],["\u003cp\u003eIt's crucial to load the map with a vector map enabled map ID, ideally with tilt and rotation activated, to fully utilize 3D camera control and functionalities.\u003c/p\u003e\n"],["\u003cp\u003eWebGL Overlay View offers lifecycle hooks like \u003ccode\u003eonAdd\u003c/code\u003e, \u003ccode\u003eonContextRestored\u003c/code\u003e, \u003ccode\u003eonDraw\u003c/code\u003e, \u003ccode\u003eonContextLost\u003c/code\u003e, \u003ccode\u003eonStateUpdate\u003c/code\u003e, and \u003ccode\u003eonRemove\u003c/code\u003e, providing control over setup, rendering, and teardown of your overlay elements.\u003c/p\u003e\n"],["\u003cp\u003eRemember to reset the GL state after rendering using methods like \u003ccode\u003erenderer.resetState()\u003c/code\u003e (Three.js) to avoid rendering conflicts and ensure proper functionality.\u003c/p\u003e\n"],["\u003cp\u003eUtilize the \u003ccode\u003ecoordinateTransformer.fromLatLngAltitude()\u003c/code\u003e helper function within \u003ccode\u003eonDraw\u003c/code\u003e to transform latitude/longitude/altitude coordinates to world/camera/screen space for accurate object placement and georeferencing.\u003c/p\u003e\n"]]],[],null,["# WebGL Overlay View\n\n\u003cbr /\u003e\n\n\n[View Sample](/maps/documentation/javascript/examples/webgl/webgl-overlay-simple)\n\nWith WebGL Overlay View you can add content to your maps using WebGL directly,\nor popular Graphics libraries like Three.js. WebGL Overlay View provides direct\naccess to the same WebGL rendering context Google Maps Platform uses to render\nthe vector basemap. This use of a shared rendering context provides benefits\nsuch as depth occlusion with 3D building geometry, and the ability to sync 2D/3D\ncontent with basemap rendering. Objects rendered with the WebGL Overlay View can\nalso be tied to latitude/longitude coordinates, so they move when you drag,\nzoom, pan, or tilt the map.\n\nRequirements\n------------\n\nTo use WebGL Overlay View, you must load the map using a map ID with the vector\nmap enabled. We strongly recommend enabling tilt and rotation when you create\nthe map ID, to allow for full 3D camera control.\n[See the overview for details](/maps/documentation/javascript/webgl).\n\nAdd WebGL Overlay View\n----------------------\n\nTo add the overlay to your map, implement `google.maps.WebGLOverlayView`, then\npass it your map instance using `setMap`: \n\n // Create a map instance.\n const map = new google.maps.Map(mapDiv, mapOptions);\n\n // Create a WebGL Overlay View instance.\n const webglOverlayView = new google.maps.WebGLOverlayView();\n\n // Add the overlay to the map.\n webglOverlayView.setMap(map);\n\nLifecycle hooks\n---------------\n\nWebGL Overlay View provides a set of hooks that are called at various times in\nthe lifecycle of the WebGL rendering context of the vector basemap. These\nlifecycle hooks are where you setup, draw, and tear down anything you want\nrendered in the overlay.\n\n- **`onAdd()`** is called when the overlay is created. Use it to fetch or create intermediate data structures before the overlay is drawn that don't require immediate access to the WebGL rendering context.\n- **`onContextRestored({gl})`** is called once the rendering context is available. Use it to initialize or bind any WebGL state such as shaders, GL buffer objects, and so on. `onContextRestored()` takes a `WebGLStateOptions` instance, which has a single field:\n - `gl` is a handle to the `WebGLRenderingContext` used by the basemap.\n- **`onDraw({gl, transformer})`** renders the scene on the basemap. The parameters for `onDraw()` is a `WebGLDrawOptions` object, which has two fields:\n - `gl` is a handle to the `WebGLRenderingContext` used by the basemap.\n - `transformer` provides helper functions to transform from map coordinates to model-view-projection matrix, which can be used to translate map coordinates to world space, camera space, and screen space.\n- **`onContextLost()`** is called when the rendering context is lost for any reason, and is where you should clean up any pre-existing GL state, since it is no longer needed.\n- **`onStateUpdate({gl})`** updates the GL state outside of the render loop, and is invoked when `requestStateUpdate` is called. It takes a `WebGLStateOptions` instance, which has a single field:\n - `gl` is a handle to the `WebGLRenderingContext` used by the basemap.\n- **`onRemove()`** is called when the overlay is removed from the map with `WebGLOverlayView.setMap(null)`, and is where you should remove all intermediate objects.\n\nFor example, the following is a basic implementation of all lifecycle hooks: \n\n const webglOverlayView = new google.maps.WebGLOverlayView();\n\n webglOverlayView.onAdd = () =\u003e {\n // Do setup that does not require access to rendering context.\n }\n\n webglOverlayView.onContextRestored = ({gl}) =\u003e {\n // Do setup that requires access to rendering context before onDraw call.\n }\n\n webglOverlayView.onStateUpdate = ({gl}) =\u003e {\n // Do GL state setup or updates outside of the render loop.\n }\n\n webglOverlayView.onDraw = ({gl, transformer}) =\u003e {\n // Render objects.\n }\n\n webglOverlayView.onContextLost = () =\u003e {\n // Clean up pre-existing GL state.\n }\n\n webglOverlayView.onRemove = () =\u003e {\n // Remove all intermediate objects.\n }\n\n webglOverlayView.setMap(map);\n\nResetting GL State\n------------------\n\nWebGL Overlay View exposes the WebGL rendering context of the basemap. Because\nof this, it is extremely important that you reset the GL state to its original\nstate when you are done rendering objects. Failure to reset the GL state is\nlikely to result in GL state conflicts, which will cause rendering of both the\nmap and any objects you specify to fail.\n\nResetting the GL state is normally handled in the `onDraw()` hook. For example,\nThree.js provides a helper function that clears any changes to the GL state: \n\n webglOverlayView.onDraw = ({gl, transformer}) =\u003e {\n // Specify an object to render.\n renderer.render(scene, camera);\n renderer.resetState();\n }\n\nIf the map or your objects fail to render, it is very likely that the GL state\nhas not been reset.\n\nCoordinate Transformations\n--------------------------\n\nThe position of an object on the vector map is specified by providing a\ncombination of latitude and longitude coordinates, as well as altitude. 3D\ngraphics, however, are specified in world space, camera space, or screen space.\nTo make it easier to transform map coordinates to these more commonly used\nspaces, WebGL Overlay View provides the\n`coordinateTransformer.fromLatLngAltitude(latLngAltitude, rotationArr,\nscalarArr)` helper function in the `onDraw()` hook that takes the following and\nreturns a `Float64Array`:\n\n- `latLngAltitude`: Latitude/longitude/altitude coordinates either as a `LatLngAltitude` or `LatLngAltitudeLiteral`.\n- `rotationArr`: `Float32Array` of euler rotation angles specified in degrees.\n- `scalarArr`: `Float32Array` of scalars to apply to the cardinal axis.\n\nFor example, the following uses `fromLatLngAltitude()` to create a camera\nprojection matrix in Three.js: \n\n const camera = new THREE.PerspectiveCamera();\n const matrix = coordinateTransformer.fromLatLngAltitude({\n lat: mapOptions.center.lat,\n lng: mapOptions.center.lng,\n altitude: 120,\n });\n camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);\n\nExample\n-------\n\nThe following is a simple example of using [Three.js](https://threejs.org), a\npopular, open source WebGL library, to place a 3D object on the map. For a\ncomplete walkthrough of using WebGL Overlay View to build the example you see\nrunning at the top of this page, try the\n[Building WebGL-accelerated Map Experiences codelab](http://goo.gle/maps-platform-webgl-codelab). \n\n const webglOverlayView = new google.maps.WebGLOverlayView();\n let scene, renderer, camera, loader;\n\n webglOverlayView.onAdd = () =\u003e {\n // Set up the Three.js scene.\n scene = new THREE.Scene();\n camera = new THREE.PerspectiveCamera();\n const ambientLight = new THREE.AmbientLight( 0xffffff, 0.75 ); // Soft white light.\n scene.add(ambientLight);\n\n // Load the 3D model with GLTF Loader from Three.js.\n loader = new GLTFLoader();\n loader.load(\"pin.gltf\");\n }\n\n webglOverlayView.onContextRestored = ({gl}) =\u003e {\n // Create the Three.js renderer, using the\n // maps's WebGL rendering context.\n renderer = new THREE.WebGLRenderer({\n canvas: gl.canvas,\n context: gl,\n ...gl.getContextAttributes(),\n });\n renderer.autoClear = false;\n }\n\n webglOverlayView.onDraw = ({gl, transformer}) =\u003e {\n // Update camera matrix to ensure the model is georeferenced correctly on the map.\n const matrix = transformer.fromLatLngAltitude({\n lat: mapOptions.center.lat,\n lng: mapOptions.center.lng,\n altitude: 120,\n });\n camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);\n\n // Request a redraw and render the scene.\n webglOverlayView.requestRedraw();\n renderer.render(scene, camera);\n\n // Always reset the GL state.\n renderer.resetState();\n }\n\n // Add the overlay to the map.\n webglOverlayView.setMap(map);"]]