Geolocation API 讓網頁在取得使用者授權後,透過 JavaScript 取得所在位置的經緯度資訊。開發者可以用它來取得目前位置,也能持續追蹤位置變化。
瀏覽器或裝置可能會使用下列一種或多種資料來源來判斷位置:
為了取得更高的準確度,許多裝置會組合多種資料來源一起定位。
Geolocation API 規範強調使用者隱私保護,必須先取得使用者明確同意,才能取得位置資訊。當頁面使用 Geolocation API 時,瀏覽器通常會跳出提示,詢問使用者是否允許分享位置。
由於位置資訊屬於敏感資料,開發者在設計應用時應注意:
Geolocation API 的使用方式相當直接:請求位置資訊,若使用者同意,瀏覽器便會回傳位置資料。
使用前可先確認瀏覽器是否支援 Geolocation API:
if (navigator.geolocation) {
console.log('Geolocation is supported.');
} else {
console.log('Geolocation is not supported in your browser.');
}
getCurrentPosition:取得目前位置資訊。watchPosition:持續監聽位置變化。兩者的基本語法如下:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
navigator.geolocation.watchPosition(successCallback, errorCallback, options);
這兩個方法都採用非同步回呼方式,主要參數如下:
successCallback:成功取得位置後呼叫的函式。errorCallback:取得位置失敗時呼叫的函式。options:定位設定,可調整精度、逾時與快取行為。
enableHighAccuracy:是否要求高精度定位,預設為 false。timeout:等待定位結果的最長時間。maximumAge:可接受快取位置的最大有效時間。若使用 watchPosition 持續追蹤位置,可在需要時以 clearWatch 停止監聽:
navigator.geolocation.clearWatch(watchId);
var watchId = navigator.geolocation.watchPosition(
function (position) {
var coords = position.coords;
console.log(coords.latitude);
console.log(coords.longitude);
console.log(coords.accuracy);
console.log(coords.altitude);
console.log(coords.altitudeAccuracy);
console.log(coords.heading);
console.log(coords.speed);
console.log(position.timestamp);
},
function (error) {
console.log('無法取得位置資訊。');
console.log(error.code);
},
{
enableHighAccuracy: true,
maximumAge: 30000,
timeout: 27000
}
);
常見錯誤碼包括: