TypeScript e Google Maps

TypeScript è un superset tipizzato di JavaScript che viene compilato in JavaScript semplice. Il codice campione riportato di seguito mostra un semplice utilizzo di Google Maps con TypeScript:

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>
Visualizza esempio

Inizia

Il progetto DefinitelyTyped è un progetto open source che gestisce i file di dichiarazione dei tipi per molti pacchetti, tra cui Google Maps. Utilizza NPM per installare i file di dichiarazione JavaScript di Google Maps dal pacchetto @types/google.maps:

npm i -D @types/google.maps

Per saperne di più, consulta i file di origine su GitHub.

Aggiungi google.maps all'opzione tsconfig types

Se il file tsconfig imposta l'opzione del compilatore types, TypeScript include solo i pacchetti @types elencati in quell'array. L'installazione di @types/google.maps non è sufficiente per abilitare il supporto di TypeScript per Google Maps e il codice che utilizza lo spazio dei nomi google non viene compilato con il seguente errore:

Error T2503: Cannot find namespace 'google'.

Per aggiungere google.maps all'array types:

{
  "compilerOptions": {
    "types": ["google.maps"]
  }
}

In alternativa, aggiungi la seguente istruzione a un file di dichiarazione incluso nel tuo progetto, ad esempio vite-env.d.ts:

/// <reference types="google.maps" />

Per saperne di più, consulta Tipi.

Pacchetti @types in conflitto

Alcune librerie potrebbero utilizzare un pacchetto diverso da @types/google.maps, il che potrebbe causare conflitti. Utilizza l'opzione del compilatore skipLibCheck per evitare problemi con tipi incoerenti:

{
  "compilerOptions": {
    "skipLibCheck": true
  }
}

Specifica typeRoots

Alcuni framework come Angular potrebbero richiedere di specificare l'opzione del compilatore typeRoots per includere i tipi installati da @types/google.maps e tutti gli altri pacchetti @types.

Per impostazione predefinita, tutti i pacchetti @types visibili sono inclusi nella compilazione. I pacchetti in node_modules/@types di qualsiasi cartella di inclusione sono considerati visibili:

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