HTML, CSS, JavaScript 코드를 사용하여 웹페이지에 Google 지도를 추가할 수 있습니다. 이 페이지에서는 웹페이지에 지도를 추가한 다음 프로그래매틱 방식으로 지도 인스턴스에 액세스하는 방법을 설명합니다.
개요
지도를 로드하려면 웹페이지에서 다음 작업을 실행해야 합니다.
- 부트스트랩 로더를 사용하여 Maps JavaScript API를 로드합니다. API 키가 전달되는 위치입니다. HTML 또는 JavaScript 소스 파일로 추가될 수 있습니다.
- HTML 페이지에 지도를 추가하고 필요한 CSS 스타일을 추가합니다.
maps라이브러리를 로드하고 지도를 초기화합니다.
gmp-map 요소를 사용하여 지도 추가하기
gmp-map 요소는 웹페이지에 Google 지도를 추가하는 데 권장되는 방법입니다.
웹 구성요소를 사용하여 생성된 맞춤 HTML 요소입니다. gmp-map 요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따릅니다.
부트스트랩이 포함된
script요소를 HTML 페이지에 추가하거나script요소 없이 JavaScript 또는 TypeScript 소스 파일에 추가합니다. API 키 및 기타 옵션으로 부트스트랩을 구성합니다. 동적 라이브러리 가져오기 또는 직접 스크립트 로딩을 선택할 수 있습니다. 이 예에서는 HTML 페이지에 동적 스크립트 로드 부트스트랩을 추가하는 방법을 보여줍니다.<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 페이지에서
gmp-map요소를 추가합니다.center에 대한 위도 및 경도 좌표 (필수),zoom에 대한 확대/축소 값 (필수), 필요한 경우map-id를 지정합니다 (고급 마커와 같은 일부 기능에 필요).
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
예시 코드 작성
TypeScript
async function initMap(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
자바스크립트
async function initMap() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>
</body>
</html>샘플 사용해 보기
div 요소 및 JavaScript를 사용하여 지도 추가하기
div 요소를 사용하여 웹페이지에 지도를 추가하려면 다음 단계를 따릅니다.
부트스트랩이 포함된
script요소를 HTML 페이지에 추가하거나script요소 없이 JavaScript 또는 TypeScript 소스 파일에 추가합니다. API 키 및 기타 옵션으로 부트스트랩을 구성합니다. 동적 라이브러리 가져오기 또는 직접 스크립트 로딩을 선택할 수 있습니다. 이 예에서는 HTML 페이지에 동적 부트스트랩을 추가하는 방법을 보여줍니다.<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%로 설정합니다. 지도가 표시되려면 CSS
height속성이 필요합니다.#map { height: 100%; }
JS 또는 TS 파일에서
maps라이브러리를 로드하고 지도를 초기화하는 함수를 만듭니다.center에 대한 위도 및 경도 좌표와zoom에 대한 확대/축소 수준을 지정합니다. 필요한 경우mapId속성을 사용하여 지도 ID를 추가합니다. 지도는 기본적으로 래스터로 설정되므로 'VECTOR' 지도 옵션을 지정하여 벡터 지도를 요청합니다. 벡터 지도 유형은 시각적 충실도를 개선하고 지도에서 기울기 및 회전을 제어하는 기능을 제공하므로 최상의 사용자 환경을 위해 권장됩니다.TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
샘플 소스 코드 전체 보기
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
자바스크립트
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } 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>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</body>
</head>
<body>
<div id="map"></div>
</body>
</html>샘플 사용해 보기
지도 인스턴스에서 속성 설정 및 가져오기
지도 인스턴스와 상호작용하려면 포함 요소를 선택합니다. 이를 위한 코드는 gmp-map 요소를 사용했는지 아니면 div 요소를 사용했는지에 따라 다릅니다.
gmp-map 요소에서 지도 인스턴스 가져오기
gmp-map 요소를 사용할 때 지도 인스턴스를 가져오려면 다음과 같이 document.querySelector를 사용하여 mapElement 인스턴스를 검색합니다.
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
그런 다음 mapElement 인스턴스에서 속성을 설정합니다.
mapElement.zoom = 8;
MapElement 클래스는 내부적으로 Map 클래스를 사용합니다. 여기에 표시된 것처럼 MapElement.innerMap 속성을 사용하여 Map 클래스에 액세스합니다.
mapElement.innerMap.setOptions({
mapTypeControl: false,
});
div 요소에서 지도 인스턴스 가져오기
div 요소를 사용하는 경우 지도 인스턴스를 가져오고 초기화 시간에 옵션을 설정합니다.
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
초기화 후 다음과 같이 map 인스턴스에서 옵션을 설정합니다.
map.setOptions({
zoom: 8,
});