解决getLocation获取当前的地理位置,报错:getLocation:fail auth deny及方法封装

1,280 阅读2分钟

问题描述

在开发微信小程序使用wx.getLocation或uni.getLocation获取当前的地理位置、速度的API时,会弹出如下的授权框,如果用户点了允许,那么就会获取到API提供的latitude纬度、longitude经度、speed速度等,但是点了拒绝就会报错:{errMsg: "getLocation:fail auth deny"},下面就将出错的问题以及开启手动授权的方法给大家介绍一下。

QQ截图20250825112801.png

问题一:

如果出现下面的报错,这就说明没有在小程序配置项中设置requiredPrivateInfos。

{errMsg: "getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json"}

解决办法:

如果是uniapp开发就需要到更目录下的manifest.json源码视图下配置,如果是微信小程序原生开发,需要到app.json中进行设置,如下:

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

将获取地理位置API的接口getLocation放置到requiredPrivateInfos属性中,详细的配置,可以参考这篇文章:blog.csdn.net/qq_18798149…

问题二:

如果出现下面的报错:

{errMsg: "getLocation:fail auth deny"}

这是在一开始概述时候说的,弹出获取位置授权框的时候,你点了拒绝,所有小程序就无法获取当前用户的位置信息,有同学可以使用了uni.getLocation的API什么错误都不显示,千万不要忘了fail回调,错误会在fail中,如下所示:

uni.getLocation({
	type: 'gcj02',
	success: (res) => {
		console.log(res);
	},
	fail: (err) => {
		console.log(err)
	}
})

解决办法:

使用我下面封装的方法,让用户手动开启权限,这个方法是通用性的,因为在微信小程序开发中,会用到很多的权限需要用户进行授权,再去获取别的API授权的时候,也可以使用该方法,更多的权限范围可以看这个文档:uniapp.dcloud.net.cn/api/other/a…

export const showAuthorize = ({ scope = 'scope.userLocation', text = '您的位置信息' } = {}) => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (setting) => {
				if (!setting.authSetting[scope]) {
					uni.showModal({
						title: '提示',
						content: `为了提供更好的服务,请允许小程序获取${text}`,
						confirmText: '去授权',
						success: (modal) => {
							if (modal.confirm) {
								uni.openSetting({
									success: (open) => {
										if (open.authSetting[scope]) {
											uni.showToast({
												icon: 'none',
												title: '授权成功'
											});
											resolve('授权成功');
										} else {
											uni.showToast({
												icon: 'none',
												title: '授权失败'
											});
											reject('授权失败');
										}
									}
								});
							} else {
								reject('授权失败');
							}
						}
					});
				}
			}
		});
	});
};

说明:

showAuthorize 方法接收一个对象;

  • scope:授权范围,可以授权常见的如:scope.userLocation、scope.address、scope.writePhotosAlbum
  • text:授权描述,如:‘保存到相册的权限’、‘您的位置信息’等

使用:

const getLocation = () => {
	uni.getLocation({
		type: 'gcj02',
		success: (res) => {
			console.log(res);
		},
		fail: async (err) => {
			console.log(err);
			try {
				let res = await showAuthorize({ text: '您的位置信息' });
				getLocation();
			} catch (err) {
				console.log(err);
			}
		}
	});
};

总结:

微信小程序需要用户授权的API还是挺多的,将手动授权的方法进行封装,后期再用的时候,直接调用接口,如果你对该方法封装有更好的建议,欢迎留言讨论。