navigator.geolocation.getCurrentPosition()
获取用户现在位置,只调用一次
getLocation() {
if (navigator.geolocation) {
// support
navigator.geolocation.getCurrentPosition((res) => {
// successed
const { coords, timestamp } = res;
console.log(coords, timestamp);
}, (res) => {
// failed
switch (res.code) {
case res.PERMISSION_DENIED:
console.log('用户拒绝获取位置权限');
break;
case res.POSITION_UNAVAILABLE:
console.log('位置信息无法使用');
break;
case res.TIMEOUT:
console.log('到达了设定的超时时间');
break;
default:
console.log('未知的错误');
}
console.log(res.message)
}, {
enableHighAccuracy: true,
maximumAge: 5000,
timeout: 3000
});
} else {
// not support
console.log(new Error('not support'));
}
}
getCurrentPosition()
方法接受三个参数,按顺序分别为:
- 成功回调(必填)
- 失败回调(可选)
- options 配置信息(可选)
成功回调包含:
- timestamp 获取位置时间
- coords 位置信息对象,包含以下属性
- accuracy(位置精确度)
- altitude(海拔高度)
- ltitudeAccuracy(海拔高度精确度)
- heading(朝向)
- latitude(纬度)
- longitude(经度)
- speed(地面速度)
失败回调包含:
- code 错误状态码,对应返回的错误码常量值
- message 错误描述语
- PERMISSION_DENIED:1(获取权限被拒)
- POSITION_UNAVAILABLE:2(位置信息不可用)
- TIMEOUT :3(到达超时设定值)
Options 参数如下:
- enableHighAcuracy (Boolean)是否获取精确位置
- maximumAge (ms)位置的缓存时间,两次调用超过此设定才重新获取,否则读取缓存
- timeout (ms)超时时间,调用时间到达此设定则返回超时错误
navigator.geolocation.watchPosition()
监听用户位置,首次获取之后,设备发生了移动,或获取到了更高精度的地理位置信息都会触发回调
watchPosition()
方法接受的参数与 getCurrentPosition()
相同,回调的返回值也相同。
const watchID = navigator.geolocation.watchPosition((position) => {
do_something(position.coords.latitude, position.coords.longitude);
});
watchPosition()
函数会返回一个 ID,唯一地标记该位置监视器。您可以将这个 ID 传给 clearWatch()
函数来停止监视用户位置。
navigator.geolocation.clearWatch(watchID);