萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML5 Geolocation API 完整指南:取得用戶位置並顯示於 Google Maps 靜態地圖

前言

HTML5 Geolocation API 允許網頁在用戶授權後取得地理座標。結合 Google Maps Static API 可直接顯示靜態地圖圖片,無需載入完整 Maps JavaScript SDK。

核心 API

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

完整實作範例

<!DOCTYPE html>
<html>
<body>
  <p id="status">點擊按鈕取得位置</p>
  <button onclick="getLocation()">定位</button>
  <div id="map"></div>

  <script>
  const statusEl = document.getElementById('status');
  const mapEl = document.getElementById('map');

  function getLocation() {
    if (!navigator.geolocation) {
      statusEl.textContent = '瀏覽器不支援 Geolocation';
      return;
    }
    statusEl.textContent = '定位中...';
    navigator.geolocation.getCurrentPosition(showMap, showError, {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    });
  }

  function showMap(position) {
    const { latitude, longitude } = position.coords;
    const latlon = `${latitude},${longitude}`;
    const imgUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${latlon}&zoom=14&size=400x300&sensor=false&key=YOUR_API_KEY`;
    mapEl.innerHTML = `地圖位置`;
    statusEl.textContent = `緯度: ${latitude}, 經度: ${longitude}`;
  }

  function showError(error) {
    const messages = {
      1: '用戶拒絕授權',
      2: '位置不可用',
      3: '請求逾時',
      0: '未知錯誤'
    };
    statusEl.textContent = `錯誤: ${messages[error.code] || error.message}`;
  }
  </script>
</body>
</html>

關鍵選項說明

選項預設說明
enableHighAccuracyfalsetrue 使用 GPS,較耗電且慢
timeoutInfinity等待回應上限毫秒數
maximumAge0接受快取位置的最大壽命(ms)

錯誤代碼對照

  • PERMISSION_DENIED (1):用戶拒絕或瀏覽器策略阻擋。
  • POSITION_UNAVAILABLE (2):裝置無法取得位置。
  • TIMEOUT (3):超過 timeout 未取得。

注意事項

  • HTTPS 必須:Chrome 50+ 僅在安全上下文(HTTPS/localhost)啟用 Geolocation。
  • Google Maps Static API 需 API Key 並啟用計費帳戶。
  • 行動裝置 GPS 定位較慢,建議 UI 給予明確載入指示。

總結

Geolocation API + Static Maps 為輕量級定位展示方案。生產環境請妥善處理授權拒絕、逾時、API Key 管理,並提供手動輸入地址作為備選。

copyright © 萬盛學電腦網 all rights reserved