웹사이트에 마커가 포함된 Google 지도 추가

소개

이 튜토리얼에서는 마커가 포함된 간단한 Google 지도를 웹페이지에 추가하는 방법을 설명합니다. 이 방법은 HTML 및 CSS에 관한 초급 또는 중급 수준의 지식과 자바스크립트에 관한 약간의 지식이 있는 사용자에게 적합합니다. 지도 만들기에 관한 고급 가이드는 개발자 가이드를 참고하세요.

이 튜토리얼을 사용하여 아래와 같은 지도를 만듭니다. 마커가 울루루 카타츄타 국립공원의 울루루(에어스 록이라고도 함)에 있습니다.


TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

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>Add 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>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "beta"});</script>
  </body>
</html>

샘플 사용해 보기

시작하기

웹페이지에 마커가 포함된 Google 지도를 만들려면 다음 세 단계를 따르세요.

  1. HTML 페이지 만들기
  2. 마커가 포함된 지도 추가
  3. API 키 가져오기

웹브라우저가 필요합니다. 지원되는 브라우저 목록에서 플랫폼에 따라 Chrome(권장), Firefox, Safari 또는 Edge와 같이 잘 알려진 브라우저를 선택합니다.

1단계: HTML 페이지 만들기

다음은 기본 HTML 웹페이지를 만들기 위한 코드입니다.

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add 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>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "beta"});</script>
  </body>
</html>

이 페이지는 제목 수준 3(h3)과 단일 div 요소가 있는 매우 기본적인 페이지입니다. 원하는 콘텐츠를 웹페이지에 추가할 수 있습니다.

코드 이해

아래 코드는 헤드와 본문으로 구성된 HTML 페이지를 만듭니다.

<html>
 <head>
 </head>
 <body>
 </body>
</html>

아래 코드를 사용하여 지도 위에 제목 수준 3을 추가할 수 있습니다.

<h3>My Google Maps Demo</h3>

아래 코드는 Google 지도를 위한 페이지 영역을 정의합니다.

<!--The div element for the map -->
<div id="map"></div>

이 단계에서는 아직 지도를 추가하지 않았으므로 div가 회색 블록으로 표시됩니다. 아래 코드는 div의 크기 및 색상을 설정하는 CSS를 설명합니다.

/* Set the size of the div element that contains the map */
#map {
    height: 400px; /* The height is 400 pixels */
    width: 100%; /* The width is the width of the web page */
}

위 코드에서 style 요소는 지도의 div 크기를 설정합니다. 지도를 표시하려면 div의 너비와 높이를 0픽셀보다 크게 설정하세요. 이 경우 div를 높이 400픽셀, 너비 100%로 설정하여 웹페이지의 너비에 맞게 표시합니다.

부트스트랩 로더는 Maps JavaScript API를 로드할 수 있도록 준비합니다(importLibrary()가 호출될 때까지 라이브러리가 로드되지 않습니다).

<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_HERE",
    // Add other bootstrap parameters as needed, using camel case.
    // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
  });
</script>

자체 API 키를 가져오는 방법은 3단계: API 키 가져오기를 참고하세요.

2단계: 마커가 포함된 지도 추가

이 섹션에서는 Maps JavaScript API를 웹페이지에 로드하는 방법과 API를 사용하는 자체 자바스크립트를 작성하여 마커가 포함된 지도를 추가하는 방법을 설명합니다.

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

위 코드에서는 initMap() 함수가 호출될 때 MapAdvancedMarkerView 라이브러리가 로드됩니다.

코드 이해

아래 코드는 새로운 Google 지도 객체를 생성하고 중심 및 확대/축소 수준을 포함한 속성을 지도에 추가합니다. 기타 속성 옵션에 대해서는 문서를 참고하세요.

TypeScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };

// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

// The map, centered at Uluru
map = new Map(
  document.getElementById('map') as HTMLElement,
  {
    zoom: 4,
    center: position,
    mapId: 'DEMO_MAP_ID',
  }
);

자바스크립트

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };
// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

// The map, centered at Uluru
map = new Map(document.getElementById("map"), {
  zoom: 4,
  center: position,
  mapId: "DEMO_MAP_ID",
});

위의 코드에서 new Map()은 새로운 Google 지도 객체를 만듭니다. center 속성은 지도의 중심을 표시할 위치를 API에 알려줍니다.

위도/경도 좌표를 가져오거나 주소를 지리적 좌표로 변환하는 방법을 자세히 알아보세요.

zoom 속성은 지도의 확대/축소 수준을 지정합니다. 확대/축소: 0은 가장 낮은 확대/축소 수준으로 지구 전체를 표시합니다. 확대/축소 값을 더 높게 설정하여 지구를 더 높은 해상도로 확대합니다.

아래 코드는 지도에 마커를 배치합니다. position 속성은 마커의 위치를 설정합니다.

TypeScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerView({
  map: map,
  position: position,
  title: 'Uluru'
});

자바스크립트

// The marker, positioned at Uluru
const marker = new AdvancedMarkerView({
  map: map,
  position: position,
  title: "Uluru",
});

마커에 대해 자세히 알아보기:

3단계: API 키 가져오기

이 섹션에서는 자체 API 키를 사용하여 Maps JavaScript API에 앱을 인증하는 방법을 설명합니다.

다음 단계에 따라 API 키를 가져옵니다.

  1. Google Cloud 콘솔로 이동합니다.

  2. 프로젝트를 만들거나 선택합니다.

  3. 계속을 클릭하여 API와 모든 관련 서비스를 사용 설정합니다.

  4. 사용자 인증 정보 페이지에서 API 키를 가져오고 API 키 제한사항을 설정합니다. 기존에 무제한 API 키가 있거나 브라우저 제한이 있는 키가 있으면 그 키를 사용할 수도 있습니다.

  5. 할당량 도난을 방지하고 API 키를 보호하려면 API 키 사용을 참고하세요.

  6. 결제를 사용 설정합니다. 자세한 내용은 사용량 및 결제를 참고하세요.

  7. 이 튜토리얼의 전체 코드를 이 페이지에서 텍스트 편집기로 복사합니다.

  8. URL의 key 매개변수 값을 자체 API 키(방금 가져온 API 키)로 바꿉니다.

    <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_HERE",
        // Add other bootstrap parameters as needed, using camel case.
        // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
      });
    </script>
    
  9. .html로 끝나는 이름(예: index.html)으로 이 파일을 저장합니다.

  10. HTML 파일을 데스크톱에서 브라우저로 드래그하여 웹브라우저에 로드합니다. 대부분의 운영체제에서는 파일을 더블클릭해도 됩니다.

도움말 및 문제 해결

  • 스타일, 속성 등의 옵션을 조정하여 지도를 맞춤설정할 수 있습니다. 지도 맞춤설정에 관한 자세한 내용은 스타일 지정지도에 그리기 가이드를 참고하세요.
  • 웹브라우저에서 개발자 도구 콘솔을 사용하여 코드를 테스트 및 실행하고 오류 보고서를 읽고 코드 관련 문제를 해결합니다.
  • 다음 단축키를 사용하여 Chrome에서 콘솔을 엽니다.
    Command+Option+J(Mac) 또는 Control+Shift+J(Windows)
  • 아래 단계에 따라 Google 지도에서 위치의 위도 및 경도 좌표를 가져옵니다.

    1. 브라우저에서 Google 지도를 엽니다.
    2. 지도에서 좌표가 필요한 정확한 위치를 마우스 오른쪽 버튼으로 클릭합니다.
    3. 표시되는 컨텍스트 메뉴에서 이곳이 궁금한가요?를 선택합니다. 지도의 하단에 카드가 표시됩니다. 카드의 마지막 행에서 위도 및 경도 좌표를 찾습니다.
  • 지오코딩 서비스를 사용하여 주소를 위도 및 경도 좌표로 변환할 수 있습니다. 개발자 가이드에서는 지오코딩 서비스 시작하기에 관한 자세한 정보를 제공합니다.