HarmonyOS鸿蒙Next中调用系统定位API失败如何解决
HarmonyOS鸿蒙Next中调用系统定位API失败如何解决
问题现象
第一次安装应用的时候调用系统定位API失败,并且失败的时候超时时间也很长。具体错误信息如下:
{"code":3301200,"message":"BussinessError 3301200: Failed to obtain the geographical location."}
背景知识
定位思路
- 检查问题代码
let requestInfo:geoLocationManager.CurrentLocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'maxAccuracy': 4
};
return geoLocationManager.getCurrentLocation(requestInfo)
- 发现问题
定位过程从问题代码可知,参数priority
值为geoLocationManager.LocationRequestPriority.FIRST_FIX
,而参数maxAccuracy
值为4
。
根据官方文档的参数说明,系统会对比GNSS或网络定位服务上报的位置信息与应用的位置信息申请。当位置信息Location
中的精度值(accuracy
)小于等于应用要求的精度值(maxAccuracy
)时,位置信息会返回给应用;否则系统将丢弃本次收到的位置信息。
建议方案根据官方参考文档中的参数说明,当priority
设置为LOW_POWER/FIRST_FIX
时,可将maxAccuracy
设置大于100
的值。因此这里建议将maxAccuracy
的值设定为100
。
- 定位结论
定位失败的原因主要是因为maxAccuracy
设置的太小,导致定位坐标被认定为不符合要求而被忽略。
解决方案
- 修改方案
根据定位结论,需要将maxAccuracy
调大,这里按照文档的建议修改为100
。
参考代码:
let startTime = new Date().getTime();
let requestInfo:geoLocationManager.CurrentLocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'maxAccuracy': 100
};
let locationChange = (err:BusinessError, location:geoLocationManager.Location):void => {
if (err) {
console.error('locationChanger: err=' + JSON.stringify(err));
}
if (location) {
console.log('locationChanger: location=' + JSON.stringify(location));
this.message = '定位信息:' + JSON.stringify(location) + '\n 花费时间:' + (new Date().getTime() - startTime) / 1000
}
};
try {
geoLocationManager.getCurrentLocation(requestInfo, locationChange);
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
};
- 方案验证
- 修改前,无法正常获取定位信息。
- 修改后,可以正常获取定位信息,并且可见实际
accuracy
约为5.65
。
更多关于HarmonyOS鸿蒙Next中调用系统定位API失败如何解决的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中调用系统定位API失败
首先检查是否已正确配置应用权限,确保在config.json
中声明了ohos.permission.LOCATION
权限。
其次,确认设备是否已开启定位服务,并检查网络连接是否正常。若使用模拟器,需确保模拟器支持定位功能。
最后,检查API调用代码是否正确,确保使用geoLocationManager
类进行定位操作。若问题依旧,可查阅官方文档或社区论坛获取更多帮助。
更多关于HarmonyOS鸿蒙Next中调用系统定位API失败如何解决的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html