웹 구성요소는 재사용 가능한 사용자설정 HTML 요소에 HTML, CSS, JS를 캡슐화하는 보편적인 W3C 표준입니다. 이러한 재사용 가능한 구성요소는 장소의 별점 평점과 같은 세부 기능에서부터 복잡한 비즈니스 로직에 이르기까지 다양합니다. 이 안내서에서는 Maps JavaScript API에서 사용할 수 있는 웹 구성요소에 대해 설명합니다.
해당 표준 자체에 대한 자세한 내용은 웹 구성요소를 참고하세요.
대상
이 문서는 웹 구성요소를 사용하여 신속하게 애플리케이션을 연구하고 개발할 수 있도록 작성되었습니다. 이를 이해하려면 HTML 및 CSS 프로그래밍 개념에 익숙해야 합니다.
지도 표시하기
웹 구성요소에 대해 가장 쉽게 배우는 방법은 예를 보는 것입니다. 다음 예는 산호세 지역의 지도를 표시합니다.
TypeScript
// This example adds a map using web components. function initMap(): void { console.log('Maps JavaScript API loaded.'); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a map using web components. function initMap() { console.log("Maps JavaScript API loaded."); } window.initMap = 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; } gmp-map { height: 400px; }
HTML
<html> <head> <title>Add a Map Web Component</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID" ></gmp-map> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta" defer ></script> </body> </html>
샘플 사용해 보기
이 예에서는 다음 사항에 유의하세요.
- Maps JavaScript API는 비동기식으로 호출됩니다. 콜백 함수는 API가 로드된 시점을 알기 위해 사용됩니다.
- 지도의 표시는
<gmp-map>
사용자설정 요소로 정의됩니다. - 지도 속성은
<gmp-map>
사용자설정 요소에서 속성을 지정하여 정의합니다. - 스타일 지정은 사용자설정 요소에 인라인으로 적용하거나 별도의 CSS 파일로 선언할 수 있습니다.
기본 지도 스타일 지정하기
지도 ID는 특정 지도 스타일 또는 지형지물과 연결된 식별자입니다. 선택사항으로 제공되는 클라우드 구성 기능을 활용하려면 클라우드 기반 지도 스타일 지정 DEMO_MAP_ID
를 자체 지도 ID로 바꾸세요.
지도 ID를 만들고 맞춤 스타일을 구성하는 방법에 대한 자세한 내용은 클라우드 기반 지도 스타일 지정을 참고하세요.
지도에 마커 추가하기
기본 제공 HTML 태그를 중첩하여 복잡한 콘텐츠 계층을 만들 수 있는 것처럼, 요소 내부에 <gmp-advanced-marker>
를 중첩하여 하나 이상의 지도 마커를 표시할 수도 있습니다.
TypeScript
// This example adds a map with markers, using web components. function initMap(): void { console.log('Maps JavaScript API loaded.'); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a map with markers, using web components. function initMap() { console.log("Maps JavaScript API loaded."); } window.initMap = 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; } gmp-map { height: 400px; }
HTML
<html> <head> <title>Add a Map with Markers using Web Components</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <gmp-map center="43.4142989,-124.2301242" zoom="4" map-id="DEMO_MAP_ID"> <gmp-advanced-marker position="37.4220656,-122.0840897" title="Mountain View, CA" ></gmp-advanced-marker> <gmp-advanced-marker position="47.648994,-122.3503845" title="Seattle, WA" ></gmp-advanced-marker> </gmp-map> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=marker&v=beta" defer ></script> </body> </html>
샘플 사용해 보기
이것은 <gmp-map>
사용자설정 요소 내부에 <gmp-advanced-marker>
요소 두 개를 추가한 것입니다. title
의 텍스트는 지정된 요소에 마우스 오버 텍스트 및 접근성 라벨을 추가로 제공합니다.
JavaScript 이벤트
웹 구성요소의 주요 이점은 사용 편의성입니다. JavaScript나 고급 프로그래밍에 대한 지식이 많지 않아도, 몇 줄의 코드를 사용하여 지도를 표시할 수 있습니다. 구현된 코드는 다른 HTML 요소의 익숙한 패턴을 따릅니다. 예를 들어 기본 브라우저 이벤트 시스템을 사용하여 지도 또는 고급 마커 액션(예: 마커 클릭)에 반응할 수 있습니다.
TypeScript
// This example adds a map using web components. function initMap(): void { console.log('Maps JavaScript API loaded.'); const advancedMarkers = document.querySelectorAll("#marker-click-event-example gmp-advanced-marker"); for (const advancedMarker of advancedMarkers) { customElements.whenDefined(advancedMarker.localName).then(async () => { advancedMarker.addEventListener('gmp-click', async () => { const infoWindow = new google.maps.InfoWindow({ //@ts-ignore content: advancedMarker.title, }); infoWindow.open({ //@ts-ignore anchor: advancedMarker }); }); }); } } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a map using web components. function initMap() { console.log("Maps JavaScript API loaded."); const advancedMarkers = document.querySelectorAll( "#marker-click-event-example gmp-advanced-marker", ); for (const advancedMarker of advancedMarkers) { customElements.whenDefined(advancedMarker.localName).then(async () => { advancedMarker.addEventListener("gmp-click", async () => { const infoWindow = new google.maps.InfoWindow({ //@ts-ignore content: advancedMarker.title, }); infoWindow.open({ //@ts-ignore anchor: advancedMarker, }); }); }); } } window.initMap = 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; } gmp-map { height: 400px; }
HTML
<html> <head> <title>Add a Map Web Component with Events</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <gmp-map id="marker-click-event-example" center="43.4142989,-124.2301242" zoom="4" map-id="DEMO_MAP_ID" > <gmp-advanced-marker position="37.4220656,-122.0840897" title="Mountain View, CA" ></gmp-advanced-marker> <gmp-advanced-marker position="47.648994,-122.3503845" title="Seattle, WA" ></gmp-advanced-marker> </gmp-map> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=marker&v=beta" defer ></script> </body> </html>
샘플 사용해 보기
이 예에서 initMap
은 Maps JavaScript API가 완전히 로드되면 필수 콜백 함수를 표시합니다. 이 코드는 각 마커에 리스너를 설정하고 각 마커를 클릭하면 정보 창을 표시합니다.
다음 단계
- Maps JavaScript API Issue Tracker에서 기능을 요청하고 버그를 신고합니다.
- 장소 개요와 같은 상위 수준의 웹 구성요소에 대한 확장 구성요소 라이브러리를 탐색합니다.