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>
適用於導航、追蹤應用:
const watchId = navigator.geolocation.watchPosition(success, error, options);
// 需停止時:navigator.geolocation.clearWatch(watchId);
在 errorCallback 中友善提示,或提供手動輸入地址的備選方案。
HTML5 取得的是 WGS84 座標(GPS 原始值),國內地圖(百度、高德、騰訊)多用 GCJ-02 或 BD-09 加密。需經過座標轉換後再疊加地圖。可用成熟庫(如 coordtransform)或後端轉換。
Chrome 50+ 規定非安全上下文(HTTP、localhost 除外)禁止使用 Geolocation。部署正式環境務必啟用 HTTPS。
enableHighAccuracy: true 優先使用 GPS(精度高、耗電、冷啟動慢);false 則用 Wi-Fi/基地台(快、省電、精度較低)。視應用場景調整。
若開發混合式 App(Android/iOS),可透過 cordova-plugin-geolocation 或 Capacitor Geolocation 外掛,呼叫原生定位權限,突破瀏覽器限制(如背景定位)。