一、背景说明

打卡签到、附近门店、运动轨迹类应用都依赖"拿到经纬度并翻译成地址"这一基础能力。OpenHarmony 7.0 Release 在设备端完善了 GNSS 上报机制,而应用侧的标准方案是 Location Kit 的 @ohos.geoLocationManager:提供 GNSS 定位、网络定位、地理编码与逆地理编码等能力。本文以"获取当前位置并翻译成地址"为主线,完整实现"权限申请 → 定位请求参数调优 → 逆地理编码 → 位置开关与错误处理"的开发流程,代码基于 API 9 及以上(含 26.0.x)。

二、技术原理

Location Kit 的定位链路由三部分组成:

  1. 权限模型:定位权限是 user_grant(运行时弹窗申请)。ohos.permission.APPROXIMATELY_LOCATION 单独授权只能拿到约 5 公里精度的模糊位置;与 ohos.permission.LOCATION 同时申请才能拿到米级精准位置;后台定位还需 ohos.permission.LOCATION_IN_BACKGROUND 加 LOCATION 型长时任务;
  2. 定位请求参数:CurrentLocationRequest 的 priority(FIRST_FIX 快速出结果/ACCURACY 精度优先)与 scenario(NAVIGATION/DAILY_LIFE_SERVICE 等场景)二选一生效,两者都 UNSET 则无法发起请求;maxAccuracy 在精确位置授权下过滤精度不满足的回调;
  3. 逆地理编码:getAddressesFromLocation(ReverseGeoCodeRequest) 把 WGS-84 坐标转成 GeoAddress 地址描述(仅支持 WGS-84 坐标系),locale 指定中文/英文,maxItems 控制返回条数。

数据流为:权限申请 → getCurrentLocation 拿经纬度 → getAddressesFromLocation 换取地址文本。

三、实现步骤

1. 权限配置 entry/src/main/module.json5(精确位置需同时声明两个位置权限):

{
  "module": {
    "requestPermissions": [
      { "name": "ohos.permission.APPROXIMATELY_LOCATION" },
      { "name": "ohos.permission.LOCATION" }
    ]
  }
}

2. 定位封装类 entry/src/main/ets/location/LocationHelper.ets(完整代码):

import { geoLocationManager } from '@kit.LocationKit';
import { abilityAccessCtrl, common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG: string = 'LocationHelper';

export class LocationHelper {
  // 运行时申请精确位置权限(两个权限一起申请)
  async requestLocationPermission(context: common.UIAbilityContext): Promise<boolean> {
    const atManager = abilityAccessCtrl.createAtManager();
    try {
      const result = await atManager.requestPermissionsFromUser(context,
        ['ohos.permission.APPROXIMATELY_LOCATION', 'ohos.permission.LOCATION']);
      return result.authResults.every(r => r === 0);
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      hilog.error(TAG, 'request failed: %{public}d', e.code);
      return false;
    }
  }

  // 获取当前位置:ACCURACY 优先级 + 10 秒超时
  async getCurrentLocation(): Promise<geoLocationManager.Location> {
    const request: geoLocationManager.CurrentLocationRequest = {
      priority: geoLocationManager.LocationRequestPriority.ACCURACY,
      scenario: geoLocationManager.LocationRequestScenario.UNSET,
      maxAccuracy: 50,          // 只接受精度 50 米以内的结果
      timeoutMs: 10000
    };
    try {
      const location = await geoLocationManager.getCurrentLocation(request);
      hilog.info(TAG, 'location: %{public}f, %{public}f (accuracy %{public}f)',
        location.latitude, location.longitude, location.accuracy);
      return location;
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      this.logError('getCurrentLocation', e);
      throw e;
    }
  }

  // 逆地理编码:经纬度换地址文本
  async getAddress(latitude: number, longitude: number): Promise<string> {
    const request: geoLocationManager.ReverseGeoCodeRequest = {
      locale: 'zh',
      latitude: latitude,
      longitude: longitude,
      maxItems: 1
    };
    try {
      const addresses: Array<geoLocationManager.GeoAddress> =
        await geoLocationManager.getAddressesFromLocation(request);
      if (addresses.length === 0) {
        return '';
      }
      return addresses[0].addressDescription ?? '';
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      this.logError('getAddressesFromLocation', e);
      throw e;
    }
  }

  // 统一错误处理:区分位置开关关闭与定位失败
  private logError(api: string, e: BusinessError): void {
    if (e.code === 3301100) {
      hilog.error(TAG, '%{public} failed: location switch is off', api);
    } else if (e.code === 3301200) {
      hilog.error(TAG, '%{public} failed: cannot obtain location', api);
    } else {
      hilog.error(TAG, '%{public} failed: %{public}d %{public}s',
        api, e.code, e.message);
    }
  }
}

3. 页面调用 entry/src/main/ets/pages/Index.ets(完整代码):

import { LocationHelper } from '../location/LocationHelper';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  private helper: LocationHelper = new LocationHelper();
  @State log: string = '就绪';

  build() {
    Column({ space: 12 }) {
      Text(this.log).fontSize(14)
      Button('定位当前地址').onClick(async () => {
        const ctx = this.getUIContext().getHostContext() as common.UIAbilityContext;
        if (!await this.helper.requestLocationPermission(ctx)) {
          this.log = '位置权限被拒绝';
          return;
        }
        try {
          const location = await this.helper.getCurrentLocation();
          const address = await this.helper.getAddress(
            location.latitude, location.longitude);
          this.log = `坐标:${location.latitude.toFixed(6)}, ` +
            `${location.longitude.toFixed(6)}\n地址:${address || '无'}`;
        } catch (err) {
          this.log = '定位失败,请检查位置开关是否打开';
        }
      })
    }
    .width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}

4. 资源文件 entry/src/main/resources/base/element/string.json:

{
  "string": [
    { "name": "module_desc", "value": "定位示例模块" },
    { "name": "app_name", "value": "LocationDemo" }
  ]
}
四、应用场景示例

打卡类应用的完整定位链路:点击打卡 → requestPermissionsFromUser 申请精确位置授权 → getCurrentLocation(ACCURACY 优先、maxAccuracy=50)拿米级坐标 → getAddressesFromLocation 换地址展示。若用户只授权了模糊位置,系统仍能返回结果但精度仅 5 公里,此时可引导用户在应用设置中开启精确位置;应用切后台后仍需定位的场景(运动轨迹)则要再叠加 LOCATION_IN_BACKGROUND 权限与 LOCATION 型长时任务。

五、技术要点
  1. 权限两两组合:单独申请 APPROXIMATELY_LOCATION 只有 5 公里模糊位置,米级精确定位必须与 LOCATION 同时申请并同时授权;两者都是 user_grant,需运行时 requestPermissionsFromUser;
  2. priority 与 scenario 二选一:两者都 UNSET 时无法发起请求(401);优先用 scenario(NAVIGATION/TRAJECTORY_TRACKING/CAR_HAILING/DAILY_LIFE_SERVICE 等场景模板),需要精细控制时再设 priority=ACCURACY/FIRST_FIX;
  3. 位置开关要前置检查:设备"位置"总开关关闭时调用接口抛 3301100,与定位失败(3301200)区分处理,前者应引导用户开开关而不是重试;
  4. 坐标系只有 WGS-84: Location Kit 输入输出均为 WGS-84 坐标系,与国内地图厂商常用的 GCJ-02(火星坐标)转换需业务自行处理,否则地图打点会有几百米偏移;
  5. timeoutMs 下限 1000ms:getCurrentLocation 默认超时 5000ms,最短 1000ms;定位时延受环境波动大,建议同步给出"定位中"的 UI 反馈;
  6. 地址结果可能为空:逆地理编码在偏远坐标可能返回空数组而非异常,展示前需判空兜底。
六、扩展建议

持续定位用 on('locationChange') 订阅流(同样的 LocationRequest 参数),配合 flush() 立即刷新缓存位置;围栏场景用 addFence 创建地理围栏并在进出时收到告警。26.0.1 Beta1 的设备端 GNSS 上报机制优化让定位时延与功耗进一步下降;如需在地图上打点展示,可叠加 Map Kit 的逆地理编码接口(需开通地图服务)获取更丰富的结构化区划与周边 POI 信息。

结语

本文用约 110 行 ArkTS 实现了定位从权限申请、参数调优到逆地理编码的完整闭环,核心是"双权限组合 + priority/scenario 二选一 + 错误码分级处理"。掌握这三点,打卡、门店、轨迹类应用的定位基座就已经立起来了。

代码仓库

本文完整示例工程已在 AtomGit 开源,为标准鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、LocationHelper 封装与页面、hvigor 构建脚本齐全,含定位权限配置),DevEco Studio 可直接打开编译运行:https://atomgit.com/NJPJI_Yang/hm-article-2026-11-29-location-kit-location-kit-atomgit

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐