TypeScript는 유형이 있는 JavaScript 상위 집합으로, 일반 JavaScript로 컴파일됩니다. 아래 샘플 코드는 TypeScript를 사용한 Google 지도의 간단한 사용 예를 보여줍니다.
TypeScript
async function init(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map')!; // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
JavaScript
async function init() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
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>
<script>
// prettier-ignore
(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: "GOOGLE_MAPS_API_KEY"
});
</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" map-id="DEMO_MAP_ID">
</gmp-map>
</body>
</html>시작하기
DefinitelyTyped 프로젝트는 Google 지도를 비롯한 많은 패키지의 유형 선언 파일을 유지 관리하는 오픈소스 프로젝트입니다. NPM을 사용하여 @types/google.maps 패키지에서 Google 지도 JavaScript 선언 파일을 설치합니다.
npm i -D @types/google.maps
자세한 내용은 GitHub의 소스 파일을 참고하세요.
tsconfig types 옵션에 google.maps 추가
tsconfig 파일이 types 컴파일러 옵션을 설정하는 경우 TypeScript는 해당 배열에 나열된 @types 패키지만 포함합니다. @types/google.maps를 설치하는 것만으로는 Google 지도에 TypeScript 지원을 사용 설정할 수 없으며 google 네임스페이스를 사용하는 코드는 다음 오류와 함께 컴파일되지 않습니다.
Error T2503: Cannot find namespace 'google'.
google.maps를 types 배열에 추가하려면 다음 안내를 따르세요.
{
"compilerOptions": {
"types": ["google.maps"]
}
}
또는 프로젝트에 포함된 선언 파일(예: vite-env.d.ts)에 다음 지시어를 추가합니다.
/// <reference types="google.maps" />
자세한 내용은 유형을 참조하세요.
@types 패키지 충돌
일부 라이브러리에서 @types/google.maps 이외의 패키지를 사용할 수 있으며 이로 인해 충돌이 발생할 수 있습니다. 일관되지 않은 유형 문제를 방지하려면 skipLibCheck 컴파일러 옵션을 사용합니다.
{
"compilerOptions": {
"skipLibCheck": true
}
}
typeRoots 지정
Angular와 같은 일부 프레임워크에서는 @types/google.maps 및 기타 모든 @types 패키지에서 설치된 유형을 포함하도록 typeRoots 컴파일러 옵션을 지정해야 할 수 있습니다.
기본적으로 표시되는 모든 @types 패키지는 컴파일에 포함됩니다.
상위 폴더의 node_modules/@types에 있는 패키지는 표시되는 것으로 간주됩니다.
{
"compilerOptions": {
"typeRoots": [
"node_modules/@types"
]
}
}