在網頁中新增 Google 地圖

您可以使用 HTML、CSS 和 JavaScript 程式碼,在網頁中新增 Google 地圖。本頁說明如何在網頁中新增地圖,然後以程式輔助方式存取地圖執行個體。

總覽

如要載入地圖,網頁必須完成下列操作:

  • 使用 Bootstrap 載入器載入 Maps JavaScript API。這個載入器會傳遞 API 金鑰。這個載入器可新增至 HTML 或 JavaScript 來源檔案。
  • 在 HTML 網頁中新增地圖,並加入所需的 CSS 樣式。
  • 載入 maps 程式庫並初始化地圖。

使用 gmp-map 元素新增地圖

gmp-map 元素是為網頁新增 Google 地圖的首選方式。 這是一個使用 Web 元件建立的自訂 HTML 元素。如要使用 gmp-map 元素在網頁中新增地圖,請按照下列步驟操作。

  1. 將包含 Bootstrap 的 script 元素新增至 HTML 網頁,或將其新增至 JavaScript 或 TypeScript 來源檔案,但不要使用 script 元素。使用 API 金鑰和任何其他選項設定 Bootstrap。您可以選擇動態匯入程式庫或直接載入指令碼。這個範例說明如何將直接指令碼載入啟動程序新增至 HTML 網頁:

    <script
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=maps,marker"
        defer
    ></script>

    進一步瞭解如何載入 Google Maps JavaScript API

  2. 在 HTML 網頁上,新增 gmp-map 元素。請指定 center 的緯度和經度座標(必填),zoom 的縮放值(必填),以及 map-id(如某些功能如高級標記,則需要指定)。要讓地圖可見,必須使用 CSS height 屬性。它既可以用 HTML 指定,也可以用 CSS 指定。為了簡單起見,本例中在 HTML 中指定了 height 樣式屬性。

    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

完整程式碼範例

<html>
  <head>
    <title>Add a Map using HTML</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>
   <!-- 
      The `defer` attribute causes the script to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises. See
      https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&libraries=maps,marker&v=weekly"
      defer
    ></script>
  </body>
</html>

使用 div 元素 (舊版) 和 JavaScript 新增地圖

如要使用 div 元素在網頁中新增地圖,請按照下列步驟操作。

  1. 將包含 bootstrap 的 script 元素新增至 HTML 頁面,或將其新增至不含 script 元素的 JavaScript 或 TypeScript 原始檔。 使用 API 金鑰和任何其他選項設定 Bootstrap。您可以選擇動態庫匯入或直接腳本載入。這個範例說明如何將動態啟動程序新增至 HTML 網頁:

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

    進一步瞭解如何載入 Google Maps JavaScript API

  2. 在 HTML 網頁上,新增 div 元素來包含地圖。

    <div id="map"></div>
  3. 在 CSS 中,將地圖高度設為 100%。地圖必須有 CSS height 屬性,才能顯示。

    #map {
      height: 100%;
    }
  4. 在 JavaScript 檔案中,建立函式來載入 maps 程式庫,並初始化地圖。指定 center 的經緯度座標,以及 zoom 的縮放等級。如果需要,請使用 map-id 屬性新增地圖 ID。

    let map;
    async function initMap() {
        const { Map } = await google.maps.importLibrary("maps");
        map = new Map(document.getElementById("map"), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
        });
    }
    initMap();

完整程式碼範例

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

JavaScript

let map;
async function initMap() {
    const { Map } = await google.maps.importLibrary("maps");
    map = new Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
    });
}
initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * 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>
  </head>
  <body>
    <div id="map"></div>

    <!-- prettier-ignore -->
    <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
  </body>
</html>

試用範例

在地圖執行個體上設定及取得屬性

如要與地圖例項互動,請選取包含元素。執行此操作的程式碼會因您使用的是 gmp-map 元素還是 div 元素而有所不同。

gmp-map 元素取得地圖例項

使用 gmp-map 元素時,如要取得地圖例項,請使用 document.querySelector 擷取 mapElement 例項,如下所示。

const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;

然後設定 mapElement 實例的屬性:

mapElement.zoom = 8;

MapElement 類別會在內部使用 Map 類別;使用 MapElement.innerMap 屬性存取 Map 類別,如下所示:

mapElement.innerMap.setOptions({
    mapTypeControl: false,
});

div 元素取得地圖實例

使用 div 元素時,請在初始化時取得地圖例項並設定選項:

map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
    mapTypeControl: false,
});

初始化後,請在 map 執行個體上設定選項,如下所示:

map.setOptions({
    zoom: 8,
});