uniapp 获取定位权限及问题解决
目录
- 步骤一:在manifest.json中配置
- 步骤二:引用文件可多页面复用的处理逻辑代码
- 注意:问题处理
- (1)报错信息1:getLocation:fail the api need to be declared in the requiredPrivateInfos fie
- (2)报错信息2:提示需要配置 permission.scope.userLocation
- (3)app.json目录:
步骤一:在manifest.json中配置
uni-app官网指南

步骤二:引用文件可多页面复用的处理逻辑代码
(1)引用文件:
import { doGetLocation } from '@/utils/getLocation.js';
(2)需要获取位置代码处执行:
doGetLocation((data)=>{console.log(data);
})
(3)getLocation.js:
// import { doGetLocation } from '@/utils/getLocation.js';
let isOpenSetting;
/*** 获取定位,兼容用户拒绝授权及相关处理(获取用户当前的授权状态 => 未同意授权位置时,引导用户打开设置界面,重新选择授权功能 => 允许后重新获取位置)*/
export function doGetLocation(callback){isOpenSetting = false; // 是否打开设置界面// 获取用户当前的授权状态uni.getSetting({success: (settingRes) => {console.log(settingRes)console.log(isOpenSetting)// 判断用户未同意授权位置时,提示并引导用户去打开设置界面,用户可重新选择授权功能if (!isOpenSetting && typeof(settingRes.authSetting['scope.userLocation']) != 'undefined' && !settingRes.authSetting['scope.userLocation']) {uni.showModal({title: '需要授权获取您的位置信息',content: '你的位置信息将用于为您提供更合适您的服务',success: (data) => {if (data.confirm) {isOpenSetting = true;// 打开设置界面uni.openSetting({success: (response) => {if(response.authSetting['scope.userLocation']){console.log('重新授权获取位置信息-同意');// 重新获取定位getLocation((data)=>{callback({isOpenSetting:isOpenSetting,...data})});}else{console.log('重新授权获取位置信息-未同意');callback({isOpenSetting:isOpenSetting,latitude : '',longitude : '',})}},fail:()=>{console.log('openSetting接口调用失败的回调函数');}})} else if (data.cancel) {console.log('showModal接口:用户点击取消未打开设置界面');callback({isOpenSetting:isOpenSetting,latitude : '',longitude : '',})}},fail: function(){console.log('showModal接口:调用失败的回调函数');}});}else{// 重新获取定位getLocation((data)=>{callback({isOpenSetting:isOpenSetting,...data})});}}})
}
/*** 获取位置*/
export function getLocation(callback){uni.getLocation({//type: 'wgs84',type: 'gcj02',success: (res)=>{console.log(res);callback({latitude : res.latitude,longitude : res.longitude,})},fail: (res)=>{console.log('用户拒绝授权获取位置信息,使用默认经纬度0 0');callback({latitude : '',longitude : '',})},complete: (res)=>{// console.log(res);// 根据位置数据更新页面数据}});
}
注意:问题处理
(1)报错信息1:getLocation:fail the api need to be declared in the requiredPrivateInfos fie
解决办法:
在app.json中加以下代码,和pages同级
"requiredPrivateInfos": ["getLocation"],
(2)报错信息2:提示需要配置 permission.scope.userLocation
解决办法:
在app.json中加以下代码,和pages同级
"permission": {"scope.userLocation": {"desc": "你的位置信息将用于小程序位置接口的效果展示"}}
(3)app.json目录:

参考:
1、uniapp中获取位置信息处理步骤
2、微信小程序getLocation报错 getLocation:fail the api need to be declared in the requiredPrivateInfos field in
3、微信官方文档-小程序配置-全局配置
