微信小程序定位权限怎么打开

一、 准备工作

既然要定位,那么肯定需要找到跟地图相关的功能API,查找微信开发文档,因为我们这里只是需要记录地位功能,不需要打开地图,所以只使用wx.getLocation 即可。查看这个方法后,发现微信只是提供了定位的经纬度,居然没有提供地点的中文名称,

我们要保存地址,肯定不能只是保存经纬度,这个一般没人能看的懂吧,而坑爹的是,找了一通,我也没发现微信小程序有提供这个功能。在网上搜索了下,百度地图和高德地图由当前经纬度获取地点的API功能。要在高德开放平台建一个定位的应用,步数很简单,第一步类型里选择“导航”,第二步平台项选择“微信小程序”即可,创建好后,会得到一个应用的key。

二、创建小程序项目

先看看小程序中的getLocation这个功能结果到底是什么

打开index.js,将page({})中onLoad 方法中的代码改成如下

wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log("-----success location-----")
        console.log(res)

        //var latitude = res.latitude
        //var longitude = res.longitude
        // wx.openLocation({
        //   latitude,
        //   longitude,
        //   scale: 18
        // })         

      },
      fail(res) {
        console.log("-----fail location-----")
        console.log(res)      
      }
    });

复制

编译后,如果是第一次使用,应该会报一个需要授权的提醒,那么先要在app.json里添加一段代码

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }

复制

,然后授权定位即可,授权成功后,在控制台就能看到打印的一个json字符串:

重要的是latitude 维度 、 longitude 经度 这2个数据 ; 其余字段的含义,可以查看文档,文档中都有详细解释。

如果把上面代码中的注释部分打开,小程序编译后显示的就是当前的地图。从地图上看,定位是不准确的,原因我没去查,我猜测就是因为通过IP去定位的,所以导致有出入,如果是在手机上查看,定位就是准确的。

三、结合高德地图API定位地点

修改index.wxml文件,将定位的地点名称显示在页面上。

<view>
<text>{
  
  {address}}</text>
<view wx:for="{
  
  {arrAddress}}">
  <text>
    {
  
  {item.address}} -- {
  
  {item.name}}
  </text>
</view>
<button open-type="openSetting">打开授权设置页</button> 
</view>

复制

第一个text标签里存放定位的地点名,循环的view标签先不要管,button是打开授权设置页用的,工具有时候会有问题,当不是第一次使用授权时,有时候不会弹出授权的对话框,可以通过这个按钮直接打开,下面我也会讲如果自定义一个对话框提醒,然后打开授权页面。

查找高德地图提供的定位API,进入高德开放平台网站,找到“开发支持”–>”微信小程序SDK” –> “参考手册”–>”基础类”,

下面的 getPoiAround(Object) 周边POI地址,getRegeo(Object) 定位地址, 均可获取到地址,但我们只是用来地位,用第二个即可。将index.js代码更新如下

const amapFile = require('../../utils/amap-wx.js')
const app = getApp()

Page({
  data: {    
    arrAddress:[],
    address:''
  },  
  onLoad: function () {
    var $that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log("-----success location-----")
        console.log(res)

        var myAmapFun = new amapFile.AMapWX({ key: app.baseData.gdLocationKey });
        myAmapFun.getRegeo({
          success: function (data) {
            
            //成功回调
            console.log("data ----- ")
            console.log(data)
            
            var address = data[0].desc + "【" + data[0].name + "】"
            $that.setData({ address: address });
          },
          fail: function (info) {
            //失败回调
            console.log(info)
            msg(info.errMsg)
          }
        });      

      },
      fail(res) {
        console.log("-----fail location-----")
        console.log(res)      
      }
    });    
    
  },
  onReady:function(){
    console.log("----onReady-----") 
  }
})

复制

编译后,在模拟器页面上就会出现定位的地点名称,同样存在误差问题,如果用手机就没有问题了。

其实看上面的代码,完全可以不需要用小程序的wx.getLocation ,直接用高德的API就能定位当前地点,这里之所以还是用wx.getLocation,是为了提醒授权的原因,但是只是这样写也是有问题的,如果是非第一次授权,只会报错,不会弹出授权的提醒对话框,这里要自己写一个提醒框。

四、自定义授权地位对话框

先将上面的代码提取到一个方法里,我这里放在了util.js中

module.exports={
  msg:msg,
  getLocation: getLocation
}
function msg(title){  
  wx.showToast({
    title: title,
    icon: "success",
    duration: 1000
  })
}
function getLocation($that) {
  var address ;
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      console.log("-----success location-----")
      console.log(res)
      var myAmapFun = new amapFile.AMapWX({ key: app.baseData.gdLocationKey });
      myAmapFun.getRegeo({
        success: function (data) {
          //成功回调
          console.log("data ----- ")
          console.log(data)          
          address = data[0].desc + "【" + data[0].name+ "】"
          $that.setData({ address: address });
        },
        fail: function (info) {
          //失败回调
          console.log(info)
          msg(info.errMsg)
        }
      })
    },
    fail(res) {
      console.log("-----fail location-----")
      console.log(res)
      //settingLoaction($that)
    }
  });
}

复制

修改index.js

const util = require('../../utils/util.js')
const app = getApp()
Page({
  data: {    
    arrAddress:[],
    address:''
  },  
  onLoad: function () {
    
    console.log("----onLoad-----")
    util.getLocation(this);
    
  }
})

复制

编译后,模拟器中也会出现定位的地点,这时候点击模拟器中“打开授权设置页”按钮,将“使用我的地理位置”开关关闭掉,重新编译小程序,控制台就会报错,但是模拟器并不会弹出授权对话框。即使只是使用高德的API,控制台也会报错:

{errCode: “0”, errMsg: “getLocation:fail auth deny”} 提示未授权定位。

判断有没有授权其实就是通过微信小程序的获取用户的当前设置里面的“scope.userLocation” 是否为true判断。

编写判断方法

function settingLoaction($that){
  wx.getSetting({    
    success: function (res) {
      console.log("-----userLocation-----")
      console.log(res)
      if (res.authSetting['scope.userLocation'] != true) {
        wx.showModal({
          title: '授权当前位置',
          content: '需要获取您的地理位置,请确认授权,否则无法获取您所需数据',
          success: function (res) {
            if (res.cancel) {//点击取消
              msg("授权失败1!")
              getLocation($that)
            } else if (res.confirm) {//点击确定
              wx.openSetting({
                success: function (res) {
                  console.log(res)
                  if (res.authSetting['scope.userLocation'] == true) {
                    msg("授权成功1!")
                    getLocation($that)
                  } else {
                    msg("授权失败2!")
                    getLocation($that)
                  }
                }
              })
            }
          }
        });
      }
    }
  });
}

复制

然后将上面的 getLocation(that)方法中获取定位失败返回函数中注释掉的settingLoaction(that) 开启即可,这时重新编译小程序,会弹出自定义的对话框。我这里写的方法是只有当用户授权了,对话框才会消失,实际用的时候,可以根据自己需要操作。

五、getPoiAround

这个是高德提供的获取经纬度周边20个地址的功能,将上面的getRegeo换成这个即可,然后将值赋给前端即可

$that.setData({ arrAddress: data.markers });

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

入伍击寇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值