萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Geolocation API 完整指南:獲取用戶地理位置的多種實作方式

核心 API:navigator.geolocation

HTML5 引入 Geolocation API,允許網頁在用戶授權後獲取經緯度座標。核心方法:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
  • successCallback(position):成功時回呼,position.coords.latitude/longitude 取得座標。
  • errorCallback(error):失敗處理(拒絕授權、逾時、不可用),error.code 對應 PERMISSION_DENIED、POSITION_UNAVAILABLE、TIMEOUT。
  • options:enableHighAccuracy(布林)、timeout(毫秒)、maximumAge(快取時間)。

完整範例:單次定位

<button onclick="getLocation()">取得我的座標</button>
<div id="demo"></div>

<script>
function getLocation() {
  const output = document.getElementById('demo');
  if (!navigator.geolocation) {
    output.textContent = '瀏覽器不支援 Geolocation';
    return;
  }
  navigator.geolocation.getCurrentPosition(
    pos => output.textContent = `緯度:${pos.coords.latitude},經度:${pos.coords.longitude}`,
    err => output.textContent = `錯誤:${err.message}`,
    { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
  );
}
</script>

持續監聽:watchPosition

適用於導航、追蹤應用:

const watchId = navigator.geolocation.watchPosition(success, error, options);
// 需停止時:navigator.geolocation.clearWatch(watchId);

常見問題與解決方案

1. 用戶拒絕授權

在 errorCallback 中友善提示,或提供手動輸入地址的備選方案。

2. 座標偏移(特別是中國大陸)

HTML5 取得的是 WGS84 座標(GPS 原始值),國內地圖(百度、高德、騰訊)多用 GCJ-02 或 BD-09 加密。需經過座標轉換後再疊加地圖。可用成熟庫(如 coordtransform)或後端轉換。

3. HTTPS 強制要求

Chrome 50+ 規定非安全上下文(HTTP、localhost 除外)禁止使用 Geolocation。部署正式環境務必啟用 HTTPS。

4. 行動裝置 GPS 與網路定位差異

enableHighAccuracy: true 優先使用 GPS(精度高、耗電、冷啟動慢);false 則用 Wi-Fi/基地台(快、省電、精度較低)。視應用場景調整。

進階整合:PhoneGap / Capacitor

若開發混合式 App(Android/iOS),可透過 cordova-plugin-geolocation 或 Capacitor Geolocation 外掛,呼叫原生定位權限,突破瀏覽器限制(如背景定位)。

隱私與合規提醒

  • 務必在隱私權政策說明位置資料用途、保存期限。
  • 遵循 GDPR、個資法等法規,提供撤銷授權機制。
  • 最小化原則:只在必要時請求定位,避免一進頁面就彈窗。
copyright © 萬盛學電腦網 all rights reserved