Geolocation.watchPosition()
Geolocation.watchPosition()
用于注册监听器,在设备的地理位置发生改变的时候自动被调用。也可以选择特定的错误处理函数。
该方法会返回一个 ID,如要取消监听可以通过 Geolocation.clearWatch()
传入该 ID 实现取消的目的。
语法
id = navigator.geolocation.watchPosition(success[, error[, options]])
参数
- success
-
成功时候的回调函数,同时传入一个
Position
对象当作参数。 - error 可选
-
失败时候的回调函数,可选,会传入一个
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);
规范
Specification |
---|
Geolocation API # watchposition-method |
浏览器兼容性
BCD tables only load in the browser
参见
- 使用地理位置定位
- 该方法属于
Geolocation
,可以通过NavigatorGeolocation.geolocation
访问。 - 取消监听的方法:
Geolocation.clearWatch()
- 另一个类似的方法:
Geolocation.getCurrentPosition()