H5 获取浏览器位置 navigator.geolocation

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);
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超喜欢你呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值