在微信小程序中,从 2023 年 7 月 开始,部分敏感接口(如 wx.getLocation
)需要在 app.json
或 ext.json
中声明 requiredPrivateInfos
字段,否则调用时会失败并返回以下错误:
css
{errMsg: "getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json"}
解决方法
在 app.json
中添加 requiredPrivateInfos
字段,声明需要使用的地理位置接口。
修改 app.json
json
{
"pages": [
"pages/index/index"
],
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于获取详细地址"
}
},
"requiredPrivateInfos": [
"getLocation"
]
}
详细步骤
-
在
app.json
中添加requiredPrivateInfos
:- 将
getLocation
添加到requiredPrivateInfos
数组中,表示需要使用wx.getLocation
接口。
- 将
-
配置
permission
:- 确保在
permission
中配置了scope.userLocation
,以便在用户授权后获取地理位置。
- 确保在
-
重新编译小程序:
- 修改
app.json
后,重新编译并运行小程序。
- 修改
完整示例代码
app.json
json
{
"pages": [
"pages/index/index"
],
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于获取详细地址"
}
},
"requiredPrivateInfos": [
"getLocation"
]
}
index.js
javascript
Page({
data: {
address: null, // 详细地址
latitude: null, // 纬度
longitude: null // 经度
},
// 获取地理位置
getLocation() {
wx.getLocation({
type: 'wgs84', // 返回 GPS 坐标
success: (res) => {
const { latitude, longitude } = res;
this.setData({
latitude,
longitude
});
this.getAddress(latitude, longitude); // 获取详细地址
},
fail: (err) => {
console.error('获取地理位置失败', err);
wx.showToast({
title: '获取位置失败',
icon: 'none'
});
}
});
},
// 根据经纬度获取详细地址 ,百度、高德和腾讯地图都行
getAddress(latitude, longitude) {
const ak = '你的百度地图AK'; // 替换为你的百度地图 AK
const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${ak}&output=json&coordtype=wgs84ll&location=${latitude},${longitude}`;
wx.request({
url,
success: (res) => {
if (res.data.status === 0) {
const { formatted_address, addressComponent } = res.data.result;
const { province, city, district, street } = addressComponent;
const address = `${province} ${city} ${district} ${street} - ${formatted_address}`;
this.setData({
address
});
} else {
console.error('获取地址失败', res.data);
}
},
fail: (err) => {
console.error('请求地址失败', err);
}
});
},
onLoad() {
// 页面加载时获取地理位置
this.getLocation();
}
});
index.wxml
xml
<view class="container">
<view class="location-info">
<text>详细地址: {{address}}</text>
<text>纬度: {{latitude}}</text>
<text>经度: {{longitude}}</text>
</view>
<button bindtap="getLocation">重新获取位置</button>
</view>
index.wxss
css
.container {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
.location-info {
margin-bottom: 20px;
}
.location-info text {
display: block;
margin-bottom: 10px;
font-size: 16px;
}
button {
margin-top: 20px;
}
注意事项
-
requiredPrivateInfos
字段:- 必须在小程序的
app.json
或ext.json
中声明。 - 支持的接口包括:
getLocation
、chooseLocation
等。
- 必须在小程序的
-
用户授权:
- 首次调用
wx.getLocation
时,会弹出授权提示框。如果用户拒绝授权,需要引导用户手动开启权限。 - 可以通过
wx.openSetting
打开设置页面,让用户重新授权。
- 首次调用
-
隐私政策:
- 获取用户地理位置时,需遵守相关隐私政策,并在小程序中明确告知用户地理位置的使用目的。
示例效果
- 页面加载时自动获取用户的地理位置,并显示详细地址(包括省、市、区、街道等信息)。
- 点击按钮可以重新获取地理位置。
通过以上方法,你可以解决 getLocation:fail the api need to be declared in the requiredPrivateInfos field
的错误,并成功获取用户的地理位置。