微信小程序获取用户位置 getLocation

发布时间 2023-04-13 14:00:26作者: ZerlinM

首先在app.config.json中配置

export default defineAppConfig({
  pages: [],
  permission: {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  },
})

方法调用:

const getLocation = () =>{
  Taro.getLocation({
    type: 'gcj02',
    isHighAccuracy: true,
    success: (res) => {
      console.log('res', res)
      const { latitude, longitude } = res;
      // do something...
      },
    fail: (err) => {
      Taro.showModal({
        title: '获取定位失败,请重新授权',
        content: '',
        success: (res) => {
          if (res.confirm) {
            getLocation()
          } else {
            // 点击取消,则退出该页面(自行做容错处理)
            Taro.switchTab({
              url: '/pages/home/index'
            })
          }
        }
      })
    }
  })
}

配置参数:
altitude 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度
complete 接口调用结束的回调函数(调用成功、失败都会执行)
fail 接口调用失败的回调函数
highAccuracyExpireTime 高精度定位超时时间(ms),指定时间内返回最高精度,该值3000ms以上高精度定位才有效果
isHighAccuracy 开启高精度定位
success 接口调用成功的回调函数
type wgs84 返回 gps 坐标,gcj02 返回可用于 Taro.openLocation 的坐标

回调函数的参数:
accuracy 位置的精确度
altitude 高度,单位 m
horizontalAccuracy 水平精度,单位 m
latitude 纬度,范围为 -90~90,负数表示南纬
longitude 经度,范围为 -180~180,负数表示西经
speed 速度,单位 m/s
verticalAccuracy 垂直精度,单位 m(Android 无法获取,返回 0)
errMsg 调用结果

附:

微信官方文档 getLocation