HarmonyOS 获取位置信息报错?

已经进行ohos.permission.LOCATION和ohos.permission.APPROXIMATELY\_LOCATION 用户授权申请,并同意授权,但是获取位置信息报错。

报错信息:

geoLocationManager promise, getCurrentLocation: error={"code":3301200,"message":"BussinessError 3301200: Failed to obtain the geographical location."} 

获取位置信息方法:

let requestInfo: geoLocationManager.LocationRequest = {
  'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
  'scenario': geoLocationManager.LocationRequestScenario.UNSET,
  'timeInterval': 1,
  'distanceInterval': 0,
  'maxAccuracy': 0
};
geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
  console.log('geoLocationManager current location: ' + JSON.stringify(result));
}).catch((error: number) => {
  console.log('geoLocationManager promise, getCurrentLocation: error=' + JSON.stringify(error));
});
阅读 530
1 个回答

可以参考下述demo:

Index页面:

import { geoLocationManager } from '@kit.LocationKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { abilityAccessCtrl, Permissions , PermissionRequestResult} from '@kit.AbilityKit'

@Entry
@Component
struct Index {

  build() {
    Row() {
      Column() {
        Button('位置授权')
          .onClick(() =>{
            getPermission(["ohos.permission.APPROXIMATELY_LOCATION"], getContext(this))
          }).margin(20)

        Button('开启定位')
          .onClick(() => {
            let requestInfo: geoLocationManager.CurrentLocationRequest = {
              'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
              'scenario': geoLocationManager.LocationRequestScenario.UNSET,
            }
            try {
              geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
                console.log('current location: ' + JSON.stringify(result));
              })
                .catch((error:BusinessError) => {
                  console.error('promise, getCurrentLocation: error=' + JSON.stringify(error));
                });
            } catch (err) {
              console.error("errCode:" + JSON.stringify(err));
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

/**
 * 请求权限
 * @param permissions getPermission(["ohos.permission.APPROXIMATELY_LOCATION"], getContext(this))
 * @param context
 * @returns
 */
export async function getPermission(permissions: Array<Permissions>, context: Context): Promise<boolean> {
  console.info("getPermission permissions:", JSON.stringify(permissions));
  let atManager: abilityAccessCtrl.AtManager
  let resultArray: Array<number> = []
  try {
    atManager = abilityAccessCtrl.createAtManager();
    let PermissionRequestResult: PermissionRequestResult = await atManager.requestPermissionsFromUser(context, permissions);
    console.info("getPermission PermissionRequestResult:", JSON.stringify(PermissionRequestResult));
    resultArray = PermissionRequestResult.authResults;
  } catch (err) {
    console.error(`get Permission error, error: ${JSON.stringify(err)}`);
  }
  for (let i = 0; i < resultArray.length; i++)
    if (resultArray[i] === 0) {
      // 用户授权,可以继续访问目标操作
      console.log('用户授权成功',)
    } else {
      // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
      console.log('用户拒绝授权',)
      return false;
    }
  return true
}

module.json5页面:

"requestPermissions": [
{
  "name": "ohos.permission.APPROXIMATELY_LOCATION",
  "reason": "$string:EntryAbility_label",
  "usedScene": {
    "abilities": [
    "EntryAbility"
    ],
    "when": "inuse"
  }
  }
]
logo
HarmonyOS
子站问答
访问
宣传栏