小程序获取定位失败
解决小程序使用getLocation方法获取定位失败,并产生报错fail the api need to be declared...
小程序获取定位失败
前因:
最近在开发某微信小程序时需要用到定位功能,获取用户地理位置加载附近门店,在开发工具调试时一直无法获取到位置,并产生报错,报错内容:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json
报错截图:

原因:
自2022年7月14日起,在使用“getLocation”时需要先行声明,用户同意后才能获取到用户的位置。
说明截图:

解决办法:
uni-app在项目根目录下点击“manifest.json”,进入源码视图,找到”mp-weixin“配置项,并添加对应声明。
添加声明:
/* 小程序特有相关 */
"mp-weixin" : {
"usingComponents" : true,
"requiredPrivateInfos": ["getLocation", "chooseLocation"],
"permission": {
"scope.userLocation": {
"desc": "您的位置信息将用于展示附近门店信息"
}
}
},源码视图截图:

mp-weixin截图:

此时小程序获取定位成功并输出经纬度。
小程序获取定位代码:
onLoad() {
uni.getLocation({
type: 'wgs84',
isHighAccuracy: true,
success: function (res) {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
},
fail(er) {
console.log(er)
}
});
}
如本文内容有所偏差或错误敬请谅解?,同时迎您在下面留言讨论,如本文怼你有所帮助请点个赞?再走吧~
