小程序onLocationChange接口的使用及注意事项

功能描述
监听实时地理位置变化事件,需结合 wx.startLocationUpdateBackground、wx.startLocationUpdate使用。

申请开通最好使用 微信小程序主体类型:工具 服务查询

参数:
function callback
实时地理位置变化事件的回调函数

参数
Object res
属性 类型 说明 最低版本
latitude number 纬度,范围为 -90~90,负数表示南纬。使用 gcj02 国测局坐标系
longitude number 经度,范围为 -180~180,负数表示西经。使用 gcj02 国测局坐标系
speed number 速度,单位 m/s
accuracy number 位置的精确度
altitude number 高度,单位 m 1.2.0
verticalAccuracy number 垂直精度,单位 m(Android 无法获取,返回 0) 1.2.0
horizontalAccuracy number 水平精度,单位 m 1.2.0

示例代码:

 const _locationChangeFn = function(res) {
  console.log('location change', res)
 }
 wx.onLocationChange(_locationChangeFn)
 wx.offLocationChange(_locationChangeFn)

首先需要请求权限,看看用户是否已经授权过位置权限,如果有权限则开始监听,没有则需要通过authorize接口授权位置

    wx.getSetting({
        success(res) {
        if(!that.data.addressName){
          wx.showLoading({
            title: '位置获取中',
          })
        }
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success () {
                if(!that.data.addressName){
                  wx.startLocationUpdate({
                    success(res){
                      console.log(res);
                    }
                  })
                }
              }
            })
          }else{
            if(!that.data.addressName){
              wx.startLocationUpdate({
                success(res){
                  console.log(res);
                }
              })
            }
          }
        }
      })
    //监听位置权限开启
    wx.onLocationChange((res)=>{
      var latitude = res.latitude,
      longitude = res.longitude;
     
      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude+','+longitude+'&get_poi=0&key=JMRBZ-44B6K-4P5JR-AWIVT-6PDB5-EFB5G',
        success(res){  
          that.recommend(res.data.result.address_component.province);  
          that.setData({
            addressName: res.data.result.address_component.province,
            city: res.data.result.address_component.city,
            district: res.data.result.address_component.district
          })
    
          wx.stopLocationUpdate({
            success(res){
              console.log(res);
              console.log('位置监听已经关闭');
            }
          })
        }
      })
    })
posted @ 2022-06-02 12:00  Dreams_log  阅读(3778)  评论(0)    收藏  举报