Geolocation.watchPosition()
Geolocation.watchPosition()
這個方法是用來註冊一個處理的函式,當使用者的裝置位置更新時,這個函式所傳入的回呼函式(callback function) 就會自動被呼叫。你也可以選擇性的定義錯誤時哪些錯誤回呼函式(error callback function) 需要被呼叫。
這個函式將回傳一組 ID 編號,此編號搭配 Geolocation.clearWatch()
函式,即可停止更新使用者的位置。
語法
id = navigator.geolocation.watchPosition(success[, error[, options]])
參數
- success
- 一個回呼函式(callback function) 會被傳入一個
Position
的物件。 - error 選擇性
- 一個選擇性的錯誤回呼函式(callback function),會被傳入一個
PositionError
的物件。 - options 選擇性
- 一個選擇性
PositionOptions
的物件。
範例
var id, target, options;
function success(pos) {
var crd = pos.coords;
if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
console.log('Congratulations, you reached the target');
navigator.geolocation.clearWatch(id);
}
}
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
}
target = {
latitude : 0,
longitude: 0
};
options = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
};
id = navigator.geolocation.watchPosition(success, error, options);
備註
如果你的應用程式是跑在 firefox OS上,請參考 geolocation wake lock,此方法可以讓你的程式在背景或螢幕關上時也能持續收到位置更新。
規格
Specification | Status | Comment |
---|---|---|
Geolocation API The definition of 'Geolocation.watchPosition()' in that specification. |
Recommendation | Initial specification. |
瀏覽器的相容性
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help! (en-US)
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 5 | 3.5 (1.9.1) | 9 | 10.60 Removed in 15.0 Reintroduced in 16.0 |
5 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | ? | 4.0 (4) | ? | 10.60 | ? |