HTML5 Geolocation API 允許網頁在用戶授權後取得地理座標。結合 Google Maps Static API 可直接顯示靜態地圖圖片,無需載入完整 Maps JavaScript SDK。
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>
| 選項 | 預設 | 說明 |
|---|---|---|
enableHighAccuracy | false | true 使用 GPS,較耗電且慢 |
timeout | Infinity | 等待回應上限毫秒數 |
maximumAge | 0 | 接受快取位置的最大壽命(ms) |
PERMISSION_DENIED (1):用戶拒絕或瀏覽器策略阻擋。POSITION_UNAVAILABLE (2):裝置無法取得位置。TIMEOUT (3):超過 timeout 未取得。Geolocation API + Static Maps 為輕量級定位展示方案。生產環境請妥善處理授權拒絕、逾時、API Key 管理,並提供手動輸入地址作為備選。