ספריות

כדי לטעון את קוד ה-JavaScript של Maps JavaScript API, צריך לכלול בדף סקריפט של רכיב טעינה להפעלת API, בפורמט הבא:

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

‫Maps JavaScript API מורכב מספריות שלא נטענות עד שמבקשים אותן באופן ספציפי. פירוק הרכיבים לספריות מאפשר ל-API לטעון ולנתח במהירות, כך שאתם צריכים לשאת בעומס הנוסף של טעינה וניתוח של ספריות רק כשאתם צריכים אותן. כשמשתמשים בייבוא דינמי של ספריות, רכיב הטעינה להפעלת API המוטבע לא טוען אף ספריה כברירת מחדל (אפילו לא core או maps). לפני שמבצעים קריאה ל-google.maps.importLibrary(), לא נטען אף חלק מ-Maps JavaScript API.

כדי לטעון ספרייה בזמן ריצה, משתמשים באופרטור await כדי לקרוא ל-google.maps.importLibrary() מתוך פונקציית async. מניחים שרק הספרייה המבוקשת נטענת, וקוראים ל-google.maps.importLibrary() לכל ספרייה שהקוד משתמש בה. לדוגמה:

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

בדוגמת הקוד הבאה אפשר לראות איך טוענים את הספריות maps ו-marker כדי לגשת למחלקות Map ו-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();

ספריות זמינות

אפשר להשתמש בספריות הבאות עם ייבוא דינמי של ספריות ותג לטעינה ישירה של סקריפט:

בדוגמה הבאה של בקשת bootstrap אפשר לראות איך מוסיפים בקשה לספריית google.maps.geometry של Maps JavaScript API לתג לטעינה ישירה של סקריפט:

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

כדי לבקש כמה ספריות, צריך להפריד ביניהן באמצעות פסיק:

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