TypeScript 和 Google 地图

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 上的源文件。

将 google.maps 添加到 tsconfig types 选项

如果您的 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)可能需要指定 typeRoots 编译器选项,以包含通过 @types/google.maps 及所有其他 @types 软件包安装的类型。

所有可见的 @types 软件包都默认包含在编译范围内。 任何封装文件夹中 node_modules/@types 目录下的软件包均被视为可见:

{
  "compilerOptions": {
    "typeRoots": [
      "node_modules/@types"
    ]
  }
}