HTML5 navigator.geolocation API 讓 Web 應用能取得使用者地理位置 (經緯度),結合逆地理編碼服務 (如百度地圖 API) 可轉換為人類可讀的地址。本文提供**生產級完整實作**:高精度選項、超時控制、錯誤碼對應、百度 API 整合、權限狀態檢查與最佳實踐。
interface Geolocation {
getCurrentPosition(successCallback, errorCallback?, options?): void;
watchPosition(successCallback, errorCallback?, options?): number; // 持續監聽
clearWatch(watchId: number): void;
}
interface PositionOptions {
enableHighAccuracy?: boolean; // 是否使用 GPS (耗電、較慢)
timeout?: number; // 等待回應上限毫秒
maximumAge?: number; // 接受快取位置的最大壽命 (毫秒)
}
interface Position {
coords: Coordinates;
timestamp: DOMTimeStamp;
}
interface Coordinates {
latitude: number; // 緯度
longitude: number; // 經度
altitude: number | null;
accuracy: number; // 水平精度 (公尺)
altitudeAccuracy: number | null;
heading: number | null; // 移動方向 (度)
speed: number | null; // 速度 (公尺/秒)
}
/**
* GeoLocator - 封裝 Geolocation API + 百度逆地理編碼
* 依賴:jQuery (僅用於 $.ajax,可替換為 fetch)
*/
class GeoLocator {
constructor(options = {}) {
this.baiduAK = options.baiduAK || 'YOUR_BAIDU_AK'; // 必須申請自己的 AK
this.defaultOptions = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 30000,
...options.positionOptions
};
}
/** 取得目前位置 (Promise 版) */
getCurrentPosition() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
return reject(new Error('GEO_UNSUPPORTED: 瀏覽器不支援地理定位'));
}
navigator.geolocation.getCurrentPosition(
pos => this._resolvePosition(pos).then(resolve).catch(reject),
err => reject(this._normalizeError(err)),
this.defaultOptions
);
});
}
/** 持續監聽位置變化 */
watchPosition(handler) {
if (!navigator.geolocation) return null;
return navigator.geolocation.watchPosition(
pos => this._resolvePosition(pos).then(handler).catch(console.error),
err => handler({ error: this._normalizeError(err) }),
this.defaultOptions
);
}
/** 停止監聽 */
clearWatch(watchId) {
navigator.geolocation?.clearWatch(watchId);
}
/** 檢查權限狀態 (Permissions API) */
async checkPermission() {
if (!navigator.permissions) return { state: 'unsupported' };
try {
const perm = await navigator.permissions.query({ name: 'geolocation' });
return { state: perm.state }; // 'granted' | 'denied' | 'prompt'
} catch (e) {
return { state: 'error', error: e };
}
}
// --- 內部方法 ---
_normalizeError(err) {
const messages = {
1: 'PERMISSION_DENIED: 使用者拒絕授權',
2: 'POSITION_UNAVAILABLE: 位置資訊不可用',
3: 'TIMEOUT: 定位請求逾時',
0: 'UNKNOWN_ERROR: 未知錯誤'
};
return new Error(messages[err.code] || messages[0]);
}
async _resolvePosition(pos) {
const { latitude, longitude, accuracy } = pos.coords;
// 呼叫百度逆地理編碼 API
const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${this.baiduAK}&output=json&coordtype=wgs84ll&location=${latitude},${longitude}`;
const response = await fetch(url);
const data = await response.json();
if (data.status !== 0) {
throw new Error(`BAIDU_GEOCODE_FAILED: ${data.status} - ${data.message}`);
}
const addr = data.result.addressComponent;
return {
coords: { latitude, longitude, accuracy },
address: {
province: addr.province?.replace('市', ''),
city: addr.city,
district: addr.district,
street: addr.street,
streetNumber: addr.street_number,
formatted: data.result.formatted_address
},
timestamp: pos.timestamp
};
}
}
// 使用範例
const locator = new GeoLocator({ baiduAK: 'YOUR_AK' });
// 按鈕觸發定位
document.getElementById('btn-locate').addEventListener('click', async () => {
try {
const result = await locator.getCurrentPosition();
console.log('定位成功:', result);
document.getElementById('txtPosition').value =
`${result.address.province}, ${result.address.city}, ${result.address.district}`;
} catch (err) {
console.error('定位失敗:', err.message);
alert(err.message);
}
});
// 頁面載入時檢查權限狀態
locator.checkPermission().then(({ state }) => {
if (state === 'denied') alert('請在瀏覽器設定中開啟定位權限');
});
enableHighAccuracy: true)enableHighAccuracy: false)。maximumAge)maximumAge: 30000 (30 秒) 可避免頻繁觸發 GPS,適合「定位按鈕」連續點擊場景。watchPosition + maximumAge: 0。| 代碼 | 常數 | 常見原因 | 建議引導文案 |
|---|---|---|---|
| 1 | PERMISSION_DENIED | 使用者拒絕、瀏覽器設定封鎖、iframe 無 allow="geolocation" | 「請在瀏覽器網址列左側圖示/設定中允許存取位置」 |
| 2 | POSITION_UNAVAILABLE | GPS 訊號弱、無 Wi-Fi/基地台資料、飛航模式 | 「請移至開闊處或開啟 Wi-Fi 提高定位精度」 |
| 3 | TIMEOUT | 超過 timeout 仍未取得位置 | 「定位逾時,請嘗試關閉飛航模式或重新整理頁面」 |
coordtype=wgs84ll。enableHighAccuracy: false + IP 定位備援)。watchPosition。// 當 Geolocation 失敗或被拒絕時,回退至 IP 定位 (精度僅城市級)
async function fallbackIpGeolocation() {
try {
const res = await fetch('https://ipapi.co/json/');
const data = await res.json();
return {
coords: { latitude: data.latitude, longitude: data.longitude, accuracy: 50000 },
address: { city: data.city, region: data.region, country: data.country_name },
source: 'ip'
};
} catch (e) {
throw new Error('IP_GEOLOCATION_FAILED');
}
}
HTML5 Geolocation API 配合逆地理編碼服務,能為 Web 應用帶來豐富的位置感知體驗。**關鍵在於:優雅處理權限拒絕/逾時/失敗、提供清晰使用者引導、嚴守隱私合規、準備 IP 定位備援**。封裝為可複用的 GeoLocator 類別,能大幅降低業務邏輯複雜度,提升開發效率與程式碼品質。