if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
pos => {
const {latitude, longitude, accuracy} = pos.coords;
console.log(`緯度: ${latitude}, 經度: ${longitude}, 精度: ${accuracy}m`);
// 發送給後端
fetch('/api/location', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({lat: latitude, lng: longitude})
});
},
err => console.error('定位失敗:', err.message),
{enableHighAccuracy: true, timeout: 10000, maximumAge: 0}
);
} else {
alert('瀏覽器不支援地理定位');
}
| 選項 | 說明 |
|---|---|
| enableHighAccuracy | true 使用 GPS,false 用 WiFi/基站 (較快、較省電) |
| timeout | 超時毫秒數,超過觸發 error 回調 |
| maximumAge | 接受快取位置最大壽命 (ms),0 即時定位 |
Chrome 50+ / Firefox 55+ **僅在 HTTPS (或 localhost) 允許調用**,HTTP 會直接拒絕並觸發 `PERMISSION_DENIED`。
fetch('https://ipapi.co/json/')
.then(r => r.json())
.then(d => console.log(`城市: ${d.city}, 經緯度: ${d.latitude}, ${d.longitude}`));
精度較低 (城市級),適合無授權場景。