HTML, CSS 및 JavaScript 코드를 사용하여 웹페이지에 Google 지도를 추가할 수 있습니다.
이 페이지에서는 gmp-map
맞춤 HTML 요소와 div
요소를 사용하는 두 가지 방법으로 웹페이지에 지도를 추가하는 방법을 보여줍니다.
개요
지도를 로드하려면 웹페이지에서 다음 작업을 실행해야 합니다.
- 부트스트랩 로더를 사용하여 Maps JavaScript API를 로드합니다. 여기에서 API 키가 전달되며 HTML 또는 자바스크립트 소스 파일에 추가할 수 있습니다.
- 지도를 HTML 페이지에 추가하고 필요한 CSS 스타일을 추가합니다.
maps
라이브러리를 로드하고 지도를 초기화합니다.
gmp-map
요소를 사용하여 지도 추가
gmp-map
요소는 웹 구성요소를 사용하여 만든 맞춤 HTML 요소입니다.
gmp-map
요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따르세요.
HTML 페이지에서 API 키 및 기타 옵션으로 구성된 부트스트랩이 포함된
script
요소를 추가합니다. 다음 부트스트랩 예에서는callback
매개변수가 필요하지 않으므로 생략되었습니다.<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
HTML 페이지에서
gmp-map
요소를 추가합니다.center
에는 위도 및 경도 좌표를,zoom
에는 확대/축소 값을 지정하세요. 이 예에서는height
스타일 속성도 지정됩니다.<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID" style="height: 400px" ></gmp-map>
예시 코드 작성
<html> <head> <title>Add a Map using HTML</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" style="height: 400px" ></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>
div
요소 및 자바스크립트를 사용하여 지도 추가
지도 로드에는 div
요소가 계속 지원됩니다. div
요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따르세요.
HTML 페이지에서 API 키 및 기타 옵션으로 구성된 부트스트랩 로더가 포함된
script
요소를 추가합니다. 또는script
태그를 제외하고 TypeScript 또는 자바스크립트 파일에 부트스트랩 로더 코드를 직접 추가합니다.<script> (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: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
HTML 페이지에서 지도를 포함할
div
요소를 추가합니다.<div id="map"></div>
CSS에서 지도 높이를 100%로 설정합니다.
#map { height: 100%; }
자바스크립트 파일에서
maps
라이브러리를 로드하고 지도를 초기화하는 함수를 만듭니다.center
에 위도 및 경도 좌표를 지정하고zoom
에 사용할 확대/축소 수준을 지정합니다.
let map; async function initMap() { const { Map } = await google.maps.importLibrary("maps"); map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } initMap();
예시 코드 작성
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; map = new Map(document.getElementById("map") as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } initMap();
JavaScript
let map; async function initMap() { const { Map } = await google.maps.importLibrary("maps"); map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } 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; }
HTML
<html> <head> <title>Simple Map</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> <div id="map"></div> <!-- prettier-ignore --> <script>(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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>