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