鸿蒙HarmonyOS获取GPS精确位置信息

参考官方文档
#1.初始化时获取经纬度信息

aboutToAppear() {
    this.getLocation()
}
async getLocation () {
    try {
      const result = await geoLocationManager.getCurrentLocation()
      AlertDialog.show({
        message: JSON.stringify(result)
      })
    }catch (error) {
      AlertDialog.show({
        message: error.message
      })
    }

}

#2.配置位置权限信息

    "requestPermissions": [
     //API9之前只申请这个就可以米级定位
      {'name':  'ohos.permission.LOCATION'},//API9之前申请的权限

      //API9后两个权限同时申请才可以获取米级定位,只下边一个权限只能精准到5公里
      {'name':  'ohos.permission.APPROXIMATELY_LOCATION'},//API9及之后需要增加申请的权限
      {
        "name": 'ohos.permission.LOCATION_IN_BACKGROUND'
      }
    ],

#3.访问设备的位置信息,必须申请权限,并且获得用户授权
在src/main/ets/entryability/EntryAbility.ts里申请

import abilityAccessCtrl from '@ohos.abilityAccessCtrl'


 async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void>  {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    let manger = abilityAccessCtrl.createAtManager()
    try {
      await manger.requestPermissionsFromUser(this.context,
        [
          'ohos.permission.MEDIA_LOCATION',
          'ohos.permission.LOCATION',
          'ohos.permission.APPROXIMATELY_LOCATION',
        ])
    } catch (err) {
      promptAction.showToast({ message: '获取位置信息失败!' })
    }
  }

鸿蒙HarmonyOS获取GPS精确位置信息_第1张图片

你可能感兴趣的:(鸿蒙HarmonyOS,harmonyos,华为)