微信小程序获取用户当前地址

有些微信小程序要获取用户的当前位置,其实小程序有自己的API(wx.getLocation(Object object))。
调用前需要用户授权

wx.getLocation({
  type: 'wgs84',
  success(res) {
    const latitude = res.latitude
    const longitude = res.longitude
    const speed = res.speed
    const accuracy = res.accuracy
  }
})

如果只是需要得到用户的当前位置,调用该接口即可。但是如果除了要得到用户的当前微信,还要得到全国所有的省、城市、区县。我们就可以调用腾讯位置服务(https://lbs.qq.com/product/miniapp/jssdk/)里面的微信小程序JavaScriptSDK。
在这里插入图片描述
第一步:申请秘钥。
需要开发者手机号码和邮箱来进行注册,然后就会分配一个秘钥给我们,后续在代码中需要用到,也是使用SDK的唯一标识。
进入key管理填写相关信息 。注意:一点要填写webService也就是你开发的电脑的IP
第二步:下载SDK。
按照他的操作来即可
第三步:在上线时,要在微信公众平台的开发设置里面设置request合法域名,不然无法正常调用。在开发过程中,可以在项目设置中设置
不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书

在这里插入图片描述
如果不设置的话将无法正常调用
下面就是调用SDK了

xxx.js

data:{
	province: '',
    provinces:'',
    city: '',
    cities:'',
}
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');//导入qqmap-wx-jssdk.js
var qqmapsdk;

用户授权获取用户信息


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let vm = this;
    vm.getUserLocation();
  },
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        // console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权,调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
   // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // console.log(JSON.stringify(res));
        //在这里就已经获取了用户的当前地址
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.getCityList();
        vm.setData({
          province: province,
          city: city,
        })
 
      },
      fail: function (res) {
        console.log('fail' + res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  //获取城市列表
  getCityList: function(){
    let vm = this;
      //调用获取城市列表接口
    qqmapsdk.getCityList({
      success: function(res) {//成功后的回调
        // console.log(res);
        // console.log('省份数据:', res.result[0]); //打印省份数据
        // console.log('城市数据:', res.result[1]); //打印城市数据
        // console.log('区县数据:', res.result[2]); //打印区县数据

        vm.setData({
          provinces:res.result[0],
          cities:res.result[1]
        })
      },
      fail: function(error) {
        console.error('fail'+error);
      },
      complete: function(res) {
        console.log(res);
      }
    });
  },

xxx.wxml

//当前位置
<view class="">
	{{province}}-{{city}}
</view>
//省份列表
<block wx:for="{{province}}">
	<view class="">{{item}}</view>
</block>
//城市列表
<block wx:for="{{cities}}">
	<view class="">{{item}}</view>
</block>

有啥子错误,敬请谅解。有啥问题,没写明白。也可以在下方评论。

发布了10 篇原创文章 · 获赞 0 · 访问量 872

猜你喜欢

转载自blog.csdn.net/qq_41309583/article/details/88691789