自定义小程序(授权)获取当前位置组件

小程序(授权)获取当前位置

(1)用户授权
(2)获取经纬度
(3)转化经纬度信息为具体位置信息

实现功能:
自定义小程序(授权)获取当前位置组件,地址既可以手动输入页也可以点击图标授权获取
(1)一个页面多处引用该组件
(2)首次拒绝授权之后,二次授权的处理

1、用户授权

(1)在app.json中配置 地理位置用途说明
{
      "permission": {
      "scope.userLocation": {
        "desc": "您的位置信息将用于小程序位置展示"
      }
}
(2)校验位置权限是否打开

使用 wx.getSetting 获取所有已授权接口。 该接口会返回一个 authSetting 对象, 里面包含了所有的授权结果。

 getUserLocation(){
      let that = this;
      // 获取用户的授权信息
      wx.getSetting({
        success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          console.log(res)
          //如果是首次进入
          if (res.authSetting['scope.userLocation'] == undefined){
              console.log("首次进入")
              that.getLocation(); 
          } else{
            //如果不是首次进入
            if (res.authSetting['scope.userLocation'] == true){
                // 授权成功之后
                that.getLocation();
            }else{
                // 未授权,提示去授权
              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 (res) {
                        console.log(res)
                        if (res.authSetting["scope.userLocation"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //调用wx.getLocation的API
                          that.getLocation();
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          }
        
        }

      })  
    },

以上代码的逻辑是:

(1)先获取用户授权列表。 获取 scope.userLocation 的值
(2)如果scope.userLocation为undefined,则第一次进入,直接调用wx.getLocation的API,如果不是首次进入,则判断有没有授权,如果已经授权则直接调用wx.getLocation的API,如果没有授权则提示去授权,如果点了确定,就使用
wx.openSetting 接口代开权限设置界面,让用户进行二次授权,授权成功之后调用wx.getLocation的API

2、获取经纬度

授权成功之后调用wx.getLocation的API获取经纬度
代码如下:

getLocation(){
  let that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        that.getLocal(latitude, longitude)
      }, fail: function (res) {
          console.log('fail' + JSON.stringify(res))
      }
    })
},

3、转化经纬度信息为具体位置信息

授权成功获取经纬度之后,借助于**微信小程序JavaScript SDK** 对返回的 latitude longitude 解析为 如下这种形式:
在这里插入图片描述
流程如下:
组件头部引入:

 var QQMapWX = require('../../utils/qqmap-wx-jssdk.js'); //引入sdk
var qqmapsdk;
//生命周期 created()里面实例化API核心类
  created(){
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: '。。。。'
    });
  },

方法里面:

    // 获取当前地理位置
  getLocal: function (latitude, longitude) {
      let that = this;
      qqmapsdk.reverseGeocoder({
        //本接口提供由坐标到坐标所在位置的文字描述的转换,输入坐标返回地理位置信息和附近poi列表。
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: function (res) {
          if(res.status==0){
               console.log(res)
                var address = res.result.address;
                let mapData = {
                  address: address,
                  dataTime: that.data.dataTime
                }
                //传递给父组件
                that.triggerEvent("getLocation", mapData)
          }  
        },fail:function(res){
             console.log(res)
        }
      })
    }

最后贴上完整的代码:

app.json
"permission": {
      "scope.userLocation": {
        "desc": "您的位置信息将用于小程序位置展示"
      }
    }

子组件中:
map.wxml

<view class="location_p" bindtap="getUserLocation">
        <image src="/images/exitIemperature/place.png" class="map_icon"></image>
</view>

map.js

const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js'); //引入sdk
var qqmapsdk;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    dataTime:{   //类型
      type: String,
      value: "",
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },
  created(){
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: '。。。。'  //申请的key
    });

  },
  ready(){

  },
  /**
   * 组件的方法列表
   */
  methods: {
     // 判断用户是否拒绝地理位置信息授权,拒绝的话重新请求授权
    getUserLocation(){
      let that = this;
      // 获取用户的授权信息
      wx.getSetting({
        success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
          // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
          // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
          console.log(res)
          //如果是第一次进入
          if (res.authSetting['scope.userLocation'] == undefined){
              console.log("第一次进入")
              that.getLocation();
              
          } else{
            //如果不是第一次进入
            if (res.authSetting['scope.userLocation'] == true){
                // 授权成功之后
                that.getLocation();
            }else{
                // 未授权,提示去授权
              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) {
                        console.log(dataAu)
                        if (dataAu.authSetting["scope.userLocation"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                          //调用wx.getLocation的API
                          that.getLocation();
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'none',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          }
        
        }

      })
       
    },
    getLocation(){
      let that = this;
        wx.getLocation({
          type: 'wgs84',
          success(res) {
            console.log(res)
            const latitude = res.latitude
            const longitude = res.longitude
            const speed = res.speed
            const accuracy = res.accuracy
            that.getLocal(latitude, longitude)
          }, fail: function (res) {
              console.log('fail' + JSON.stringify(res))
          }
        })
    },
    // 获取当前地理位置
    getLocal: function (latitude, longitude) {
      let that = this;
      qqmapsdk.reverseGeocoder({
        //本接口提供由坐标到坐标所在位置的文字描述的转换,输入坐标返回地理位置信息和附近poi列表。
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: function (res) {
          if(res.status==0){
              console.log(res)
            var address = res.result.address;
            let mapData = {
              address: address,
              dataTime: that.data.dataTime
            }
            //传递给父组件
            that.triggerEvent("getLocation", mapData)
          }  
        },fail:function(res){
             console.log(res)
        }
      })
    }

  }
})

map.wxss

/* components/map/map.wxss */
.location_p{
    width: 60rpx;
    text-align: right;
   line-height: 82rpx;
    height: 82rpx;
}
.location_p .map_icon{
  width: 40rpx;
  height: 40rpx;
}
.default_status{
   color: #787878;
    padding-left: 10rpx;
    line-height: 82rpx;
    height: 82rpx;
}
.curr_status{
   color: #000;
    padding-left: 10rpx;
    line-height: 82rpx;
    height: 82rpx;
}

父组件:

  <view class="info_li">
        <view class="info_name">位置:</view>
          <view class="info_text">
               <input type="text"  placeholder="点击图标获取位置" value='{{amAddress}}' bindinput='pickerChange'/>
                  <!-- 引入组件的地方 -->
                <mapLocation dataTime="{{dataTimeAm}}"  class="map_box" bind:getLocation="getLocation"></mapLocation>
            </view> 
  </view>
  data:{
         dataTimeAm:'am', //区分上午还是下午地图组件
         dataTimePm:'pm',
         amAddress: "", //上午位置
         pmAddress:"",
  },
   pickerChange: function (e) {
    this.setData({
      amAddress: e.detail.value
    })
  },
      // 获取位置
  getLocation(e){
    console.log(e.detail)
    var mapData = e.detail;
    if (mapData.dataTime == 'am') {
      this.setData({
        amAddress: mapData.address
      })
    } else {
      this.setData({
        pmAddress: mapData.address
      })
    }    
  },

效果图如下:

在这里插入图片描述

点击取消,授权失败
在这里插入图片描述
第二次进入,点击确定。跳转到设置页面
在这里插入图片描述

设置页面:
在这里插入图片描述

打开开关,返回之后发现已经获取到位置:
在这里插入图片描述
在这里插入图片描述
注意:贴上微信开发平台最新的信息
在这里插入图片描述

Tip:如果回显地址的地方直接使用input会发现,内容过长的情况下不支持换行,并且在失去焦点的情况下,不支持滑动,就会出现地址在页面显示不全的情况,此时也许你会想到用textarea,但是其实小程序原生的textarea坑也很多,想用input,又想可以回显换行,这种情况下,可以前往
解决input内容过长,内容显示不全的问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 微信小程序是一种轻量化的应用程序,可以在微信中直接使用。它具有快速开发、轻便易用等优点。其中,微信小程序map组件可以用于定位当前位置。 首先,在小程序开发工具中添加map组件,可以利用微信提供的API进行对地图的操作。然后,在页面上添加按钮或者其他交互方式,触发定位功能。可以通过微信提供的wx.getLocation接口获取当前地理位置,将其坐标转换为经纬度等信息,再在地图上显示出来。 微信小程序map组件还可以加入自定义的标记点、路线等功能。比如,可以在地图上设置一个目标地点,当用户到达该地点时进行提醒。除此之外,还可以将地图与其他组件联动,实现更多实用性功能。 总之,通过微信小程序map组件定位当前位置可以在很多场景下得到运用,例如共享单车、打车等领域,也为用户带来更加便利和舒适的出行体验。 ### 回答2: 微信小程序的定位功能可以让用户在地图上查看自己的当前位置,并且可以进行定位导航等一系列应用操作。 要使用微信小程序的定位功能,首先需要获取用户的授权。用户可以通过点击相关按钮进行授权,同时小程序需要向用户说明获取授权的作用和用途。 获取授权后,就可以通过小程序调用微信地图API,实现对用户当前位置的定位功能。用户当前位置会在地图上进行标注,并且可以实现定位导航、查询周边信息等功能。 除了获取授权和调用API之外,开发者还需要考虑到用户体验和隐私保护等方面。比如,在页面显示用户当前位置时要注意保护用户隐私,使用合适的地图标识等。 总体来说,微信小程序的定位功能可以方便用户在不同场景下使用地图,同时也增加了小程序的实用性。对开发者而言,需要注意用户隐私和开发规范等方面的问题,以保证用户体验和小程序功能的完善。 ### 回答3: 微信小程序中提供了一种方便的方法,可以使用map组件定位当前位置。这个组件可以用来显示地图和标记位置,还可以选择地图的种类和放大程度。在小程序中,我们只需要在wxml文件中添加map组件,然后在js文件中调用API即可进行位置定位。 首先,我们需要引入wx.getLocation() API,这个API可以获得当前用户的地理位置。通过这个API获得的经纬度信息,我们可以通过地图定位到用户的当前位置。在js文件中添加如下代码,就可以实现定位操作: ``` wx.getLocation({ type: 'gcj02', success(res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy } }) ``` 其中,type参数可以设置定位方式,gcj02表示国测局加密经纬度坐标,还有其他选项,具体可以查看文档。通过上述代码,我们得到用户的经纬度位置,并可以通过map组件显示在地图上。 ``` <map latitude="{{latitude}}" longitude="{{longitude}}" scale="{{scale}}" markers="{{markers}}" show-location="{{true}}" /> ``` 最后,在wxml文件中加入map组件即可。其中,latitude和longitude参数分别表示经纬度位置,scale参数表示显示比例尺,markers参数可以设置地图标记,show-location参数表示是否显示定位标记。 总之,通过微信小程序的map组件和wx.getLocation() API,我们可以轻松实现定位当前位置的操作。这一功能在很多小程序中都会用到,比如地图导航、外卖送餐等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值