Biblioteche

Per caricare il codice JavaScript per l'API Maps JavaScript, devi includere uno script del boot loader di bootstrap nella pagina, nel seguente formato:

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

L'API Maps JavaScript è costituita da librerie che non vengono caricate finché non le richiedi espressamente. La suddivisione dei componenti in librerie consente all'API di caricare e analizzare rapidamente, in modo da sostenere l'overhead aggiuntivo di caricamento e analisi delle librerie solo quando ne hai bisogno. Quando utilizzi l'importazione dinamica delle librerie, il boot loader incorporato non carica alcuna libreria per impostazione predefinita (nemmeno core o maps); prima di chiamare google.maps.importLibrary(), non viene caricata alcuna parte dell'API Maps JavaScript.

Per caricare una libreria in fase di runtime, utilizza l'operatore await per chiamare google.maps.importLibrary() all'interno di una funzione async. Presumi che venga caricata solo la libreria richiesta e chiama google.maps.importLibrary() per ogni libreria utilizzata dal tuo codice. Ad esempio:

const { Map } = await google.maps.importLibrary("maps");

L'esempio di codice seguente mostra il caricamento delle librerie maps e marker per accedere alle classi Map e AdvancedMarkerElement:

TypeScript

async function init(): Promise<void> {
    // Request the needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);
    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map')!;

    // Get the inner map.
    const innerMap = mapElement.innerMap;

    // Set map options.
    innerMap.setOptions({
        mapTypeControl: false,
    });

    // Add a marker positioned at the map center (Uluru).
    new AdvancedMarkerElement({
        map: innerMap,
        position: mapElement.center,
        title: 'Uluru/Ayers Rock',
    });
}
void init();

JavaScript

async function init() {
    // Request the needed libraries.
    const [{ AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('maps'),
    ]);
    // Get the gmp-map element.
    const mapElement = document.querySelector('gmp-map');

    // Get the inner map.
    const innerMap = mapElement.innerMap;

    // Set map options.
    innerMap.setOptions({
        mapTypeControl: false,
    });

    // Add a marker positioned at the map center (Uluru).
    new AdvancedMarkerElement({
        map: innerMap,
        position: mapElement.center,
        title: 'Uluru/Ayers Rock',
    });
}
void init();

Librerie disponibili

Le seguenti librerie sono disponibili per l'utilizzo con l'importazione dinamica delle librerie e il tag di caricamento diretto degli script:

La seguente richiesta di bootstrap illustra come aggiungere una richiesta per la libreria google.maps.geometry dell'API Maps JavaScript al tag di caricamento diretto dello script:

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

Per richiedere più librerie, separale con una virgola:

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