웹페이지에 Google 지도 추가하기

HTML, CSS, JavaScript 코드를 사용하여 웹페이지에 Google 지도를 추가할 수 있습니다. 이 페이지에서는 gmp-map 맞춤 HTML 요소 및 div 요소를 사용하여 웹페이지에 지도를 추가하는 2가지의 방법을 설명합니다.

개요

지도를 로드하려면 웹페이지에서 다음 작업을 실행해야 합니다.

  • 부트스트랩 로더로 Maps JavaScript API를 로드합니다. API 키가 여기로 전달되며, HTML 또는 JavaScript 소스 파일로 추가될 수 있습니다.
  • HTML 페이지에 지도를 추가하고 필요한 CSS 스타일을 추가합니다.
  • maps 라이브러리를 로드하고 지도를 초기화합니다.

gmp-map 요소를 사용하여 지도 추가하기

gmp-map 요소는 웹 구성요소로 생성된 맞춤 HTML 요소입니다. gmp-map 요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따릅니다.

  1. HTML 페이지에서 API 키로 구성된 부트스트랩 및 모든 기타 옵션을 포함하는 script 요소를 추가합니다. 다음 예시의 부트스트랩에서는 callback 매개변수가 필요하지 않으므로 누락되었습니다.

    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
    
  2. 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 요소 및 JavaScript를 사용하여 지도 추가하기

지도를 로드하기 위해 div 요소를 계속 사용할 수 있습니다. div 요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따릅니다.

  1. HTML 페이지에서 API 키로 구성된 부트스트랩 로더 및 모든 기타 옵션을 포함하는 script 요소를 추가합니다. 또한 TypeScript 파일이나 JavaScript 파일에 script 태그를 제외한 부트스트랩 로더 코드를 바로 추가합니다.

    <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>
    
  2. HTML 페이지에서 div 요소를 추가하여 지도를 포함시킵니다.

    <div id="map"></div>
    
  3. CSS에서 지도 높이를 100%로 설정합니다.

    #map {
      height: 100%;
    }
    
  4. JavaScript 파일에서 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>

샘플 사용해 보기