uniapp获取当前位置检测及定位权限——支持App、微信小程序
首先,祝天下母亲,节日快乐~
文章目录
- uniapp获取当前位置检测及定位权限——支持App、微信小程序
- 效果图
- 新增 兼容小程序方法
- manifest
Tips:
- 上一篇介绍 App端 uniapp获取当前位置及检测授权状态
- 在 基础上 兼容
微信小程序
,使用方法是一样的,这里就不再介绍了,需要朋友们直接copy
即可使用哦~;
效果图
新增 兼容小程序方法
location.js
新增 兼容小程序方法- 新增方法:
- getSetting
- showConfirm
- openSetting
// #ifdef APP-PLUS
import permision from '@/common/js/permission.js'
// #endif
import store from '@/store/index.js'var modalInfo = {content: '为了您更好的体验App蓝牙功能,需要获取位置信息,请点击设置开启定位权限',confirmText: '设置'
}export async function getLocation(cb) {// #ifdef APP-PLUSlet status = await checkPermission();if (status !== 1) {return status;}// #endif// #ifdef MP-WEIXINlet status = await getSetting();if (status === 2) {showConfirm();return;}// #endifif (typeof cb == 'function') cb && typeof cb == 'function' && cb(status)doGetLocation();
}export const doGetLocation = () => {uni.getLocation({success: (res) => {store.commit('SET_LOCATION', {lng: res.longitude,lat: res.latitude});console.log('当前位置:', res.longitude, res.latitude);},fail: (err) => {if (err.errMsg.indexOf("auth deny") >= 0) {uni.showToast({title: '访问位置被拒绝',icon: 'none'})} else {uni.showToast({title: err.errMsg,icon: 'none'})}}})
}async function checkPermission() {let status = permision.isIOS ? await permision.requestIOS('location') :await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');if (status === null || status === 1) {status = 1;} else if (status === 2) {uni.showModal({content: '系统定位已关闭',showCancel: false,success: function(res) {}})} else if (status.code) {uni.showModal({content: status.message})} else {uni.showModal({content: modalInfo.content,confirmText: modalInfo.confirmText,success: function(res) {if (res.confirm) {permision.gotoAppSetting();}}})}return status;
}/*** 获取用户的当前设置*/
function getSetting() {return new Promise((resolve, reject) => {uni.getSetting({success: (res) => {if (res.authSetting['scope.userLocation'] === undefined) {resolve(0);return;}if (res.authSetting['scope.userLocation']) {resolve(1);} else {resolve(2);}}});});
}/*** 拒绝授权:弹窗可以和App共用,根据平台调用方法,自行修改下即可;*/
function showConfirm() {uni.showModal({content: modalInfo.content,confirmText: modalInfo.confirmText,showCancel: true,success: (res) => {if (res.confirm) {openSetting();}}})
}/*** 如果拒绝授权,调起微信小程序设置界面*/
function openSetting() {uni.openSetting({success: (res) => {if (res.authSetting && res.authSetting['scope.userLocation']) {doGetLocation();}},fail: (err) => {}})
}const location = {getLocation
}
export default location;
manifest
- 在
manifest.js
中,添加"requiredPrivateInfos" : [ "getLocation" ]
"mp-weixin" : {"appid" : "xxxx","setting" : {"urlCheck" : false,"es6" : true,"postcss" : true,"minified" : true},"usingComponents" : true,"lazyCodeLoading" : "requiredComponents","permission" : {"scope.userLocation" : {"desc" : "你的位置信息将用于为了更好体验蓝牙功能"}},"libVersion" : "latest","requiredPrivateInfos" : [ "getLocation" ]
},