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

소개

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

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

아래 섹션에는 이 튜토리얼에서 지도를 만드는 데 필요한 코드 전체가 표시되어 있습니다.

TypeScript

// Initialize and add the map
function initMap(): void {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: uluru,
    }
  );

  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

자바스크립트

// Initialize and add the map
function initMap() {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

window.initMap = initMap;

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 */
}

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>

    <!--
      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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></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>

    <!--
      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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></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를 설명합니다.

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* 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%로 설정하여 웹페이지의 너비에 맞게 표시합니다.

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

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

TypeScript

// Initialize and add the map
function initMap(): void {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: uluru,
    }
  );

  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

자바스크립트

// Initialize and add the map
function initMap() {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

window.initMap = initMap;

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 */
}

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>

    <!--
      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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

샘플 사용해 보기

코드 이해

아래 코드에서 script는 지정된 URL에서 API를 로드합니다.

<script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

위 코드에서 callback 매개변수는 API가 로드된 후 initMap 함수를 실행합니다. async 속성을 사용하면 API가 로드되는 동안 브라우저가 페이지의 나머지 부분을 계속 파싱할 수 있습니다. API가 로드되면 브라우저가 일시중지되고 즉시 스크립트가 실행됩니다. key 매개변수에는 API 키가 포함됩니다.

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

아래 코드에는 웹페이지가 로드될 때 지도를 초기화하고 추가하는 initMap 함수가 포함되어 있습니다. script 태그를 사용하여 initMap 함수가 포함된 자체 자바스크립트를 포함하세요.

  function initMap() {}

document.getElementById() 함수를 추가하여 웹페이지에서 지도 div를 찾습니다.

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

TypeScript

// The location of Uluru
const uluru = { lat: -25.344, lng: 131.031 };
// The map, centered at Uluru
const map = new google.maps.Map(
  document.getElementById("map") as HTMLElement,
  {
    zoom: 4,
    center: uluru,
  }
);

자바스크립트

// The location of Uluru
const uluru = { lat: -25.344, lng: 131.031 };
// The map, centered at Uluru
const map = new google.maps.Map(document.getElementById("map"), {
  zoom: 4,
  center: uluru,
});

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

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

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

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

TypeScript

// The marker, positioned at Uluru
const marker = new google.maps.Marker({
  position: uluru,
  map: map,
});

자바스크립트

// The marker, positioned at Uluru
const marker = new google.maps.Marker({
  position: uluru,
  map: map,
});

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

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 async
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
    

  9. .html로 끝나는 이름(예: index.html)으로 이 파일을 저장합니다.

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

도움말 및 문제 해결

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

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