uni-app微信小程序uni.getLocation获取位置;authorize scope.userLocation需要在app.json中声明permission;小程序用户拒绝授权后重新授权
需求:點擊按鈕獲取當前微信位置,以及點擊拒絕授權后,下次點擊還可以拉起授權窗口;
拒絕授權后重新拉起授權操作:
直接授權操作:
一、問題1:報authorize scope.userLocation需要在app.json中聲明permission字段;
原因:因為微信小程序從2019年1月14日起新提交發布的版本若未填寫地理位置用途說明,則將無法正常調用地理位置相關接口;
解決辦法: 在manifest.json文件中,mp-weixin屬性下配置permission獲取地理位置的權限
代碼如下:直接復制黏貼對應位置即可
二、點擊進行獲取位置:
以上的配置好后,如果直接使用uni.getLocation()方法,不判斷是否有獲取的權限, 就去獲取 ,那么第一次獲取時候會讓你授權,確認則可以獲取到;但如果拒絕,則獲取不到,且以后都無法喚起授權也無法獲取到。
此時就遇到問題2:微信小程序如何在用戶拒絕授權申請后再次拉起授權窗口?
解決方法:思路是在用戶點擊拒絕授權時,添加彈框wx.showModal();在彈框內再次讓用戶選擇是否授權以及調用權限wx.openSetting();
不要慌:直接復制以下代碼即可解決,記得配置permission:
<template><view><button type="" @click="getLocation">獲取位置</button><view>經度:{{x}}</view><view>緯度:{{y}}</view></view> </template><script> export default {data () {return {x: 0,y: 0}},methods: {getLocation () {let that = this// 獲取用戶是否開啟 授權獲取當前的地理位置、速度的權限。uni.getSetting({success (res) {console.log(res)// 如果沒有授權if (!res.authSetting['scope.userLocation']) {// 則拉起授權窗口uni.authorize({scope: 'scope.userLocation',success () {//點擊允許后--就一直會進入成功授權的回調 就可以使用獲取的方法了uni.getLocation({type: 'wgs84',success: function (res) {that.x = res.longitudethat.y = res.latitudeconsole.log(res)console.log('當前位置的經度:' + res.longitude)console.log('當前位置的緯度:' + res.latitude)uni.showToast({title: '當前位置的經緯度:' + res.longitude + ',' + res.latitude,icon: 'success',mask: true})}, fail (error) {console.log('失敗', error)}})},fail (error) {//點擊了拒絕授權后--就一直會進入失敗回調函數--此時就可以在這里重新拉起授權窗口console.log('拒絕授權', error)uni.showModal({title: '提示',content: '若點擊不授權,將無法使用位置功能',cancelText: '不授權',cancelColor: '#999',confirmText: '授權',confirmColor: '#f94218',success (res) {console.log(res)if (res.confirm) {// 選擇彈框內授權uni.openSetting({success (res) {console.log(res.authSetting)}})} else if (res.cancel) {// 選擇彈框內 不授權console.log('用戶點擊不授權')}}})}})} else {// 有權限則直接獲取uni.getLocation({type: 'wgs84',success: function (res) {that.x = res.longitudethat.y = res.latitudeconsole.log(res)console.log('當前位置的經度:' + res.longitude)console.log('當前位置的緯度:' + res.latitude)uni.showToast({title: '當前位置的經緯度:' + res.longitude + ',' + res.latitude,icon: 'success',mask: true})}, fail (error) {uni.showToast({title: '請勿頻繁調用!',icon: 'none',})console.log('失敗', error)}})}}})}}, } </script><style> </style> 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的uni-app微信小程序uni.getLocation获取位置;authorize scope.userLocation需要在app.json中声明permission;小程序用户拒绝授权后重新授权的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux资源管理器编写,Linux系统
- 下一篇: 图片复印如何去除黑底_如何处理打印出来的