微信小程序首页地理位置显示

<view class="content">
   <view class="">
     定位地址:{{city}}
   </view>
</view>

Page({

  /**
   * 页面的初始数据
   */
  data: {
    locationStatus:false,//是否定位过
    city:'定位中...'
  },

  onShow() {
    // 判断是否定位过,如果没有定位,就执行定位
    if(this.data.locationStatus==false){
      this.dingwei()
      wx.setStorageSync('locationStatus',true)
      this.setData({
        locationStatus:wx.getStorageSync('locationStatus')
      })
    }else{ //若定位过,直接把本地的定位地址赋值
      this.setData({
        city:wx.getStorageSync('city')
      })
    }
    
  },
  onLoad() {
  },
  

    // 打开设置
    openConfirm(){
      wx.showModal({
        title: '请求授权当前位置',
        content: '需要获取您的地理位置,请确认授权',
        success:(res=>{
          if(res.confirm){
            wx.openSetting();// 打开地图权限设置
          }else if(res.cancel){
            wx.showToast({
              title: '你拒绝了授权,无法获得周边信息',
              icon: 'none',
              duration: 1000                            
            })
          }
        }) 
      })
    },
    // 定位
    dingwei(){
      var that = this
      // 授权
      wx.authorize({
          scope: 'scope.userLocation',
          success() {
          // 定位
             wx.getLocation({
                 type: 'gcj02',
                 success: function (res) {
                     console.log('当前位置的经度:' + res.longitude);
                     console.log('当前位置的纬度:' + res.latitude);
                 var longitude = res.longitude
                 var latitude= res.latitude
                 var location = latitude+','+longitude
                 console.log(location)
            // 逆解析地址 个人秘钥
                 wx.request({
                     url: 'https://apis.map.qq.com/ws/geocoder/v1/?key=个人秘钥&get_poi=1',
                   data:{
                     location:location
                   },
                   method: "get",
                     success: (res) => {
                         console.log(res.data.result.address);
                wx.setStorageSync('city',res.data.result.address)
                that.setData({
                  city:wx.getStorageSync('city')
                })
               
                     }
                 });
                 }
             });
          },
        fail(){    // 拒绝授权
          that.openConfirm();
          console.log("你拒绝了授权,无法获得周边信息")
        }
      })
    },


})
境随心转而悦,心随境转而烦
原文地址:https://www.cnblogs.com/tomingto/p/15405567.html