一个使用位置的业务场景,使用定位,偶现拿不到位置,并伴随"m\_singleLocation is nullptr!"日志异常。日志输出如下:
07-16 14:54:11.762 32196-32196 C02300/Locator_standard E [(GenerateCompleteContext:456)]m_singleLocation is nullptr!
一开始出现在三方库中,以为是三方库的问题,遂自己使用原生接口实现,概率降低,但仍会出现(常出现在第一次进入该页面)。
调用位置相关代码如下:
async updateLocation(){
let isAuth = await AuthUtil.checkPermissions('ohos.permission.APPROXIMATELY_LOCATION') && await AuthUtil.checkPermissions('ohos.permission.LOCATION');
if (!isAuth) {
//获取用户授权
let code = await AuthUtil.reqPermissionsList(['ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.LOCATION']);
if (!code) {
//授权失败
return
}
}
//解析定位
let current = await geoLocationManager.getCurrentLocation({
scenario: geoLocationManager.LocationRequestScenario.DAILY_LIFE_SERVICE,
maxAccuracy: 0,
timeoutMs: 1000
});
let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": current.latitude, "longitude": current.longitude, "maxItems": 1};
try {
let result :geoLocationManager.GeoAddress[] = await geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest)
if (result){
//获取到位置信息
this.positionStr = result[0]?.placeName || ''
this.hasGetPos = true
let des:string[] | undefined =result[0]?.descriptions
let streetCode : string = des?.[1] || ''
if (streetCode.length >0) {
let areaCode:string = streetCode.slice(0, 6);
//请求水印信息,包括天气等
let getWaterInfoReq :GetWaterInfoApi = new GetWaterInfoApi(areaCode,this.positionStr)
this.waterInfo = await getWaterInfoReq.getWaterInfo()
console.error("水印信息:"+JSON.stringify(this.waterInfo))
}
}
} catch (err) {
console.error("errCode:" + JSON.stringify(err));
}
}
m\_singleLocation is nullptr导致定位失败,可以参考一下这个链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/errorcode-geolocationmanager-V5\#section3301200-定位失败未获取到定位结果
同时,精度似乎设置的有问题,当scenario为DAILY\_LIFE\_SERVICE/NO\_POWER或者priority为LOW\_POWER/FIRST\_FIX时,建议设置maxAccuracy为大于100的值,建议修改一下,可以参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-geolocationmanager-V5\#locationrequest