Thư viện

Để tải mã JavaScript cho API JavaScript của Maps, bạn cần thêm một tập lệnh trình nạp khởi động vào trang của mình, theo biểu mẫu sau:

<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 được tạo thành từ các thư viện không được tải cho đến khi bạn yêu cầu cụ thể. Việc chia các thành phần thành các thư viện cho phép API tải và phân tích cú pháp nhanh chóng, vì vậy, bạn chỉ phải chịu thêm chi phí chung khi tải và phân tích cú pháp các thư viện khi cần. Khi sử dụng nhập thư viện động, trình tải khởi động nội tuyến sẽ không tải bất kỳ thư viện nào theo mặc định (thậm chí không phải core hoặc maps); trước khi gọi google.maps.importLibrary(), không có phần nào của Maps JavaScript API được tải.

Để tải thư viện trong thời gian chạy, hãy sử dụng toán tử await để gọi google.maps.importLibrary() từ trong hàm async. Giả sử chỉ thư viện được yêu cầu được tải và gọi google.maps.importLibrary() cho mỗi thư viện mà mã của bạn sử dụng. Ví dụ:

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

Ví dụ về mã sau đây cho thấy cách tải cả thư viện maps và marker để truy cập vào các lớp Map và 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();

Thư viện có sẵn

Bạn có thể sử dụng các thư viện sau đây bằng tính năng nhập thư viện động và thẻ tải tập lệnh trực tiếp:

Yêu cầu khởi động sau đây minh hoạ cách thêm yêu cầu cho thư viện google.maps.geometry của API JavaScript Maps vào thẻ tải tập lệnh trực tiếp:

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

Để yêu cầu nhiều thư viện, hãy phân tách các thư viện bằng dấu phẩy:

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