Geolocation.watchPosition()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Geolocation.watchPosition()
用于注册监听器,在设备的地理位置发生改变的时候自动被调用。也可以选择特定的错误处理函数。
该方法会返回一个 ID,如要取消监听可以通过 Geolocation.clearWatch()
传入该 ID 实现取消的目的。
语法
js
watchPosition(success)
watchPosition(success, error)
watchPosition(success, error, options)
参数
- success
-
成功时候的回调函数,同时传入一个
Position
对象当作参数。 - error 可选
-
失败时候的回调函数,可选,会传入一个
PositionError
对象当作参数。 - options 可选
-
一个可选的
PositionOptions
对象。
示例
js
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 # watchposition-method |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
watchPosition |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
参见
- 使用地理位置定位
- 该方法属于
Geolocation
,可以通过NavigatorGeolocation.geolocation
访问。 - 取消监听的方法:
Geolocation.clearWatch()
- 另一个类似的方法:
Geolocation.getCurrentPosition()