微信小程序之自动获取定位

注意这个是结合腾讯位置服务
另外还有在app.js中添加
“permission”: {
“scope.userLocation”: {
“desc”: “你的位置信息将用于小程序定位”
}
},

/**
 * 自动获取定位信息,utils/utils.jsz中
 */
function getLocation(app, that, qqmapsdk) {
  var tempAddrInfo = wx.getStorageSync('tempAddrInfo') || {};//获取缓存
  wx.getLocation({//获取当前的地理位置、速度。
    type: 'gcj02',
    latitude: tempAddrInfo.latitude || '',
    longitude: tempAddrInfo.longitude || '',
    success(res) {
      // console.log(222)          
      tempAddrInfo.latitude = res.latitude;
      tempAddrInfo.longitude = res.longitude;
      //api逆地址解析
      qqmapsdk.reverseGeocoder({
        //location: res.latitude + ',' + res.longitude,
        success: function (v) {
          // console.log(v)
          var d_quyu = v.result.address_component.province + v.result.address_component.city + v.result.address_component.district
          tempAddrInfo.province = v.result.address_component.province;
          tempAddrInfo.city = v.result.address_component.city;
          tempAddrInfo.district = v.result.address_component.district;
          tempAddrInfo.address = v.result.address;
          tempAddrInfo.address_small = d_quyu;
          wx.setStorageSync('tempAddrInfo', tempAddrInfo);
          that.setData({
            tempAddrInfo: tempAddrInfo,
          })
          console.log(tempAddrInfo)
          //刷新数据
          //that.goRefreshDatas();
        },
        fail: function (v) {},
      })
    },
    fail(res) {
      wx.showModal({
        title: '提示',
        content: '无法获取您的位置信息,请到设置—>微信—>位置中检查是否打开定位服务并允许访问您的定位。并重新进入小程序',
        success: function (res) {
          if (res.confirm) { //这里是点击了确定以后
            wx.switchTab({
              url: '/pages/index/index'
            })
          } else { //这里是点击了取消以后
            wx.switchTab({
              url: '/pages/index/index'
            })
          }
        }
      })
      that.setData({
        usrLocation: false,
        isXianshi: true
      })
    }
  })
}

index.js页面调取

//注意头部引用文件
var util = require("../utils/util.js");//引入函数库
var app = getApp();//引入全局配置
var QQMapWX = require('../utils/qqmap-wx-jssdk.min.js');//腾讯位置服务公共密钥
var qqmapsdk = new QQMapWX({
  key: app.globalData.tengxunMapKey//腾讯位置服务密钥
});
//比如说刷新页面执行
 onShow: function () {
   var that =this;
   if (wx.getSetting) {
     wx.getSetting({ //获取用户授权
       success(res) {
         //console.log(res)
         if (res.authSetting['scope.userLocation'] == true) { //已授权
           util.getLocation(app, that, qqmapsdk);
         } else if (res.authSetting['scope.userLocation'] == undefined) { //空
           util.getLocation(app, that, qqmapsdk);
         } else if (res.authSetting['scope.userLocation'] == false) { //未授权
           wx.showModal({
             title: '请求授权当前位置',
             content: '需要获取您的地理位置,请确认授权',
             success: function (res) {
               if (res.confirm) { //点击了确认
                 wx.openSetting({
                   success(data) {
                     if (data.authSetting["scope.userLocation"] == true) {
                       util.getLocation(app, that, qqmapsdk);
                     } else {
                       return;
                     }
                   }
                 })
               }
             }
           })
         }
       }
     })
   } else {
     // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
     wx.showModal({
       title: '提示',
       content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
     })
   }

 },

题外话:PHP的距离判断

/**
 * 根据经纬度算距离,返回结果单位是公里,先纬度,后经度
 * @param $lat1	纬度
 * @param $lng1	经度
 * @param $lat2	纬度
 * @param $lng2	经度
 * @return float|int
 */
function maps_getDistance($lat1, $lng1, $lat2, $lng2){
    $EARTH_RADIUS = 6371;
    $radLat1 = maps_rad($lat1);
    $radLat2 = maps_rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = maps_rad($lng1) - maps_rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 1000) / 1000;
    return $s;
}
function maps_rad($d){
    return $d * M_PI / 180.0;
}
//使用
if($latitude && $longitude && $rs["map_lat"] && $rs["map_lng"]){
	$dis_val = maps_getDistance($latitude, $longitude, $rs["map_lat"], $rs["map_lng"]);
	$juli = '约'.($dis_val<1 ? ($dis_val*1000).'m' : $dis_val.'km').'';
}

2021-05-18 获取用户详细位置信息优化2.0

/**
 * 自动获取定位信息
 */
function getLocation(that, qqmapsdk) {
  if (wx.getSystemInfoSync().locationEnabled == false) {
    wx.showModal({
      title: '提示',
      content: '请打开手机定位',
      showCancel: false
    })
    return;
  }
  if (wx.getSetting) {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.confirm) {
               wx.openSetting({
                  success(data) {
                    if (data.authSetting["scope.userLocation"] == true) { //如果授权成功
                      wx.getLocation({ //获取当前位置信息
                        type: 'gcj02',
                        success(res) {
                          qqmapsdk_dizhi(that, qqmapsdk, res.latitude, res.longitude);
                          console.log(123)
                        }
                      })
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: '授权失败',
                        showCancel: false
                      })
                      wx.removeStorage('tempAddrInfo_dingwei');
                      return;
                    }
                  }
                })
              } else if (res.cancel) {
                wx.showModal({
                  title: '提示',
                  content: '授权失败',
                  showCancel: false
                })
                wx.removeStorage('tempAddrInfo_dingwei');
                return;
              }
            }
          })
        } else {
          wx.getLocation({ //授权获取当前位置信息
            type: 'gcj02',
            success(res) {
              qqmapsdk_dizhi(that, qqmapsdk, res.latitude, res.longitude);
            },
            fail(res) { //请求频率第一次返回当前未知信息,剩余返回第一次位置信息
              wx.showModal({
                title: '提示',
                content: '无法获取您的位置信息,请到设置—>微信—>位置中检查是否打开定位服务并允许访问您的定位。并重新进入小程序',
              })
            }
          })
        }
      }
    })
  } else {
    // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
    })
    return;
  }
}
/**
 * 地址解析
 */
function qqmapsdk_dizhi(that, qqmapsdk, latitude, longitude) {
  qqmapsdk.reverseGeocoder({
    location: latitude + ',' + longitude,
    success: function (v) {
      var tempAddrInfo_dingwei = wx.getStorageSync('tempAddrInfo_dingwei') || {};
      var d_quyu = v.result.address_component.province + v.result.address_component.city + v.result.address_component.district
      tempAddrInfo_dingwei.province = v.result.address_component.province; //省份
      tempAddrInfo_dingwei.city = v.result.address_component.city; //城市
      tempAddrInfo_dingwei.district = v.result.address_component.district; //区
      tempAddrInfo_dingwei.address = v.result.address; //详细地址
      tempAddrInfo_dingwei.address_dquyu = d_quyu; //省市区
      tempAddrInfo_dingwei.latitude = v.result.location.lat; //坐标
      tempAddrInfo_dingwei.longitude = v.result.location.lng; //坐标
      wx.setStorageSync('tempAddrInfo_dingwei', tempAddrInfo_dingwei);
      //更新当前页面的位置请求数据
      var formDatas = that.data.formDatas;
      formDatas.tempAddrInfo_dingwei = tempAddrInfo_dingwei;
      that.setData({
        formDatas,
      })
      //刷新数据
      // that.goRefreshDatas();
    },
    fail: function (v) {},
  })
}
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值