Thư viện

Để tải mã JavaScript cho API JavaScript của Maps, bạn cần đưa tập lệnh trình tải bootstrap vào trang của mình, theo 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>

API JavaScript của Maps bao gồm 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 thư viện cho phép API tải (và phân tích cú pháp) nhanh chóng. Bạn chỉ phải chịu thêm chi phí tải và phân tích cú pháp thư viện khi cần.

Tải các thư viện bổ sung trong thời gian chạy bằng cách sử dụng toán tử await để gọi importLibrary() từ trong hàm async. Ví dụ:

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

Ví dụ về mã sau đây cho thấy việc tải cả thư viện MapAdvancedMarkerElement:

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();
// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

Thư viện có sẵn

Bạn có thể sử dụng các thư viện sau đây với tính năng nhập thư viện độngthẻ 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>