> 技术文档 > 微信小程序报错getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ex

微信小程序报错getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ex


文章目录

    • 1、背景
    • 2、问题解决

1、背景

调试基础库版本 3.7.7,使用如下代码进行地理授权

wx.authorize({ scope: \'scope.userLocation\', success() { console.log(\'用户授权成功\'); // 授权成功,获取位置 wx.getLocation({ type: \'wgs84\', // 默认为 wgs84,返回 GPS 坐标 success(res) { console.log(\'当前位置:\', res.latitude, res.longitude); }, fail(err) { console.error(\'获取位置失败:\', err); } }); }, fail() { wx.showModal({ title: \'授权提示\', content: \'我们需要获取您的位置信息以提供更好的服务,是否授权?\', success(res) { if (res.confirm) { wx.openSetting({ success(settingRes) {  if (settingRes.authSetting[\'scope.userLocation\']) { console.log(\'用户已授权地理位置\');  } } }); } } }); }});

已在 app.json中加上权限配置

 \"permission\": { \"scope.userLocation\": { \"desc\": \"你的位置信息将用于小程序位置接口的效果展示\" } }

在使用小程序地理位置信息授权过程中出现如下错误:

The config file \"ext.json\" doesn\'t existgetLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json

2、问题解决

该报错说明调用 getLocation API 时,必须在 app.json/ext.json 文件中的 requiredPrivateInfos 字段声明该 API。

在官方文档中找到该字段说明:使用以下8个地理位置相关接口时,需要声明该字段,否则将无法正常使用

地理位置接口 说明 getFuzzyLocation 获取模糊地理位置 getLocation 获取精确地理位置 onLocationChange 监听实时地理位置变化事件 startLocationUpdate 接收位置消息(前台) startLocationUpdateBackground 接收位置消息(前后台) chooseLocation 打开地图选择位置 choosePoi 打开POI列表选择位置 chooseAddress 获取用户地址信息

所以完整的地理授权配置应如下:

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

错误已被解决,控制台将打印成功信息