在網站中加入含有標記的 Google 地圖

簡介

本教學課程說明如何在網頁中加入含有標記的簡易 Google 地圖。適用對象為具備 HTML 和 CSS 初級或中級知識,且對 JavaScript 不太瞭解的使用者。如需建立地圖的進階指南,請參閱開發人員指南

以下是您將在本教學課程中建立的地圖。標記位於烏魯魯卡塔丘塔國家公園的烏魯魯 (又稱艾爾斯岩)。


TypeScript

// 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

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>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

試用範例

開始使用

在網頁上建立含有標記的 Google 地圖時,步驟共有三個:

  1. 建立 HTML 網頁
  2. 加入含有標記的地圖
  3. 取得 API 金鑰

您需要使用網路瀏覽器。請從支援的瀏覽器清單中,根據您使用的平台選擇 Google Chrome (建議使用)、Firefox、Safari 或 Edge 等常見瀏覽器。

步驟 1:建立 HTML 網頁

以下是基本 HTML 網頁程式碼:

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

請注意,這是非常基本的網頁,包含第三層標題 (h3) 和一個 div 元素。您可以在網頁中加入任意內容。

瞭解程式碼

下方程式碼會建立 HTML 網頁,包含標題和內文。

<html>
 <head>
 </head>
 <body>
 </body>
</html>

您可以使用下方程式碼,在地圖上方加入第三層標題。

<h3>My Google Maps Demo</h3>

下方程式碼定義網頁上要加入 Google 地圖的區域。

<!--The div element for the map -->
<div id="map"></div>

在教學課程的這個階段中,您尚未加入地圖,因此 div 會顯示為灰色區塊。下方程式碼說明用以設定 div 尺寸和顏色的 CSS。

/* Set the size of the div element that contains the map */
#map {
    height: 400px; /* The height is 400 pixels */
    width: 100%; /* The width is the width of the web page */
}

在上述程式碼中,style 元素會設定地圖的 div 尺寸。請將 div 寬度和高度設為大於 0 像素,以便顯示地圖。在本例中,div 的高度設為 400 像素,寬度設為 100%,依照網頁的完整寬度顯示地圖。

Bootstrap 載入器會準備 Maps JavaScript API 進行載入 (在呼叫 importLibrary() 前不會載入任何程式庫)。

<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_HERE",
    // Add other bootstrap parameters as needed, using camel case.
    // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
  });
</script>

如要瞭解如何自行取得 API 金鑰,請參閱「步驟 3:取得 API 金鑰」一節。

步驟 2:加入含有標記的地圖

本節說明如何在網頁中載入 Maps JavaScript API,以及如何自行編寫 JavaScript,以使用 API 加入含有標記的地圖。

TypeScript

// 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

在上述程式碼中,系統呼叫 initMap() 函式時會載入 MapAdvancedMarkerView 程式庫。

瞭解程式碼

下方程式碼會建立新的 Google 地圖物件,並將屬性加入地圖,包括中心點和縮放等級。請參閱其他屬性選項的說明文件。

TypeScript

// 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 { AdvancedMarkerView } = 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',
  }
);

JavaScript

// 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 { AdvancedMarkerView } = await google.maps.importLibrary("marker");

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

在上述程式碼中,new Map() 會建立新的 Google 地圖物件。center 屬性會向 API 指出地圖的中心點。

進一步瞭解如何取得經緯度座標,或將地址轉換成地理座標

zoom 屬性會指定地圖的縮放等級。「縮放:0」是最低的縮放等級,會顯示整個地球。調高縮放等級,就能以較高的解析度放大地球。

下方程式碼會在地圖上加入標記。position 屬性會設定標記的位置。

TypeScript

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

JavaScript

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

進一步瞭解標記:

步驟 3:取得 API 金鑰

本節說明如何使用您自己的 API 金鑰,向 Maps JavaScript API 驗證應用程式。

取得 API 金鑰的步驟如下:

  1. 前往 Google Cloud 控制台

  2. 建立或選取所需專案。

  3. 按一下「繼續」以啟用 API 和所有相關服務。

  4. 在「憑證」頁面上,取得 API 金鑰 (並設定 API 金鑰限制)。注意:如果您目前有不受限制的 API 金鑰,或是設有瀏覽器限制的金鑰,可以使用該金鑰。

  5. 如要避免配額竊用行為及保護 API 金鑰,請參閱「使用 API 金鑰」。

  6. 啟用計費功能。詳情請參閱「用量與計費」一文。

  7. 從這個網頁複製教學課程中的整段程式碼,然後貼到文字編輯器中。

  8. 將網址中的 key 參數值換成您自己的 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_HERE",
        // Add other bootstrap parameters as needed, using camel case.
        // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
      });
    </script>
    
  9. 儲存這個檔案,檔名結尾為 .html (例如 index.html)。

  10. 將 HTML 檔案從桌面拖曳到網路瀏覽器中以進行載入。在大部分的作業系統上,也可以按兩下檔案進行載入。

提示和疑難排解

  • 您可以調整樣式和屬性等選項來自訂地圖。如要進一步瞭解如何自訂地圖,請參閱「樣式」和「在地圖上繪圖」的指南。
  • 您可以在網路瀏覽器中,使用開發人員工具控制台測試及執行程式碼、閱讀錯誤報告,以及解決程式碼問題。
  • 在 Chrome 中使用下列鍵盤快速鍵開啟控制台:
    Command+Option+J 鍵 (Mac) 或 Control+Shift+J 鍵 (Windows)。
  • 請按照下方步驟操作,取得 Google 地圖上某個地點的經緯度座標。

    1. 在瀏覽器中開啟 Google 地圖。
    2. 在地圖上,對需要座標的精確位置按一下滑鼠右鍵。
    3. 從顯示的內容選單中選取「這是哪裡?」,地圖就會在畫面底部顯示資訊卡,並於卡上最後一列提供經緯度座標。
  • 使用地理編碼服務即可將地址轉換成經緯度座標,而您可以在開發人員指南找到開始使用地理編碼服務的詳細資訊。