文档开发者中心
我的

鸿蒙应用开发实战:基于LocationKit的完整定位与逆地理编码指南

浏览101发布于2026-07-16 05:37山东

在鸿蒙应用开发中,获取设备位置信息是许多场景(如天气查询、地图导航、签到打卡、本地生活服务等)的基础能力。本文将基于 @kit.LocationKit 提供的 geoLocationManager 模块,系统讲解从权限申请到获取详细地址的完整定位流程,并结合实际代码演示每一步的实现细节。

一、权限配置:声明与申请

在鸿蒙系统中,位置信息属于用户隐私数据,应用必须在 module.json5 中声明所需权限,并在运行时向用户申请授权。

1.1 配置文件声明权限

在 entry/src/main/module.json5 的 requestPermissions 数组中声明定位权限:

收起
自动换行
深色代码主题
复制
{
 "module": {
   "requestPermissions": [
     {
       "name": "ohos.permission.APPROXIMATELY_LOCATION",
       "reason": "$string:location_reason",
       "usedScene": {
         "abilities": ["EntryAbility"],
         "when": "inuse"
       }
     },
     {
       "name": "ohos.permission.LOCATION",
       "reason": "$string:location_reason",
       "usedScene": {
         "abilities": ["EntryAbility"],
         "when": "inuse"
       }
     }
   ]
 }
}

关键细节:

  • ohos.permission.APPROXIMATELY_LOCATION:模糊位置权限,精度约5公里。
  • ohos.permission.LOCATION:精准位置权限,精度可达米级别。
  • 重要规则:鸿蒙的设计要求必须先申请模糊位置权限,才能申请精准位置权限。若只申请 LOCATION 而不申请 APPROXIMATELY_LOCATION,系统不会弹出授权弹窗。
  • 权限名称字符串末尾不能带空格,否则无法匹配对应权限。
  • reason 字段应配置在资源文件中,用于向用户说明申请权限的目的。
  • 如果应用需要在后台持续获取位置,还需额外申请 ohos.permission.LOCATION_IN_BACKGROUND 权限,并申请长时任务。

1.2 运行时动态申请权限

在页面或Ability中通过 abilityAccessCtrl 动态申请权限:

收起
自动换行
深色代码主题
复制
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';

async requestPermissions(context: common.UIAbilityContext): Promise<boolean> {
 const atManager = abilityAccessCtrl.createAtManager();
 const permissions: Permissions[] = [
   'ohos.permission.APPROXIMATELY_LOCATION',
   'ohos.permission.LOCATION'
 ];
 try {
   const result = await atManager.requestPermissionsFromUser(context, permissions);
   // 检查授权结果:0 表示授权成功
   const allGranted = result.authResults.every((r: number) => r === 0);
   return allGranted;
 } catch (error) {
   console.error(`权限申请失败: ${error.code}, ${error.message}`);
   return false;
 }
}

关键细节:

  • 同时传入两个权限,系统通常会一次性弹出授权弹窗,而非两次弹窗。
  • 授权结果 authResults 中 0 表示授权成功,非 0 表示拒绝。
  • 权限申请建议在 onPageShow 生命周期中触发,确保页面可见时发起请求。

二、检查位置服务开关

即使应用获得了定位权限,如果用户在系统设置中关闭了“位置服务”总开关,应用仍然无法获取位置信息。因此,在发起定位请求前必须先检查位置开关状态:

收起
自动换行
深色代码主题
复制
import { geoLocationManager } from '@kit.LocationKit';

isLocationEnabled(): boolean {
 try {
   return geoLocationManager.isLocationEnabled();
 } catch (error) {
   console.error('检查位置开关失败', error);
   return false;
 }
}

关键细节:

  • isLocationEnabled() 返回 true 表示位置开关已开启,false 表示已关闭。
  • 如果开关未开启,可以引导用户跳转到系统设置页面开启定位。从 API 12 开始,可使用 abilityAccessCtrl.requestGlobalSwitch() 拉起全局开关设置弹框。

三、获取缓存位置(省电优先)

对于不需要实时位置、对精度要求不高的场景,建议优先获取系统缓存的最新位置,这样可以显著降低功耗。如果系统没有缓存位置,该方法会返回 null:

收起
自动换行
深色代码主题
复制
getLastLocation(): geoLocationManager.Location | null {
 try {
   return geoLocationManager.getLastLocation();
 } catch (error) {
   console.error('获取缓存位置失败', error);
   return null;
 }
}

关键细节:

  • 缓存位置是系统最近一次定位结果,可能有一定延迟。
  • 如果对位置的新鲜度有要求,可以获取缓存位置后将时间戳与当前时间对比,若新鲜度不满足预期再发起新的定位请求。
  • 此方式几乎不消耗额外电量,适合作为定位流程的第一步。

四、单次定位:获取当前位置

对于需要获取当前精确位置的场景(如签到打卡、服务推荐等),使用 getCurrentLocation 发起单次定位请求:

收起
自动换行
深色代码主题
复制
async getCurrentLocation(timeoutMs: number = 10000): Promise<geoLocationManager.Location | null> {
 try {
   const request: geoLocationManager.SingleLocationRequest = {
     locatingPriority: geoLocationManager.LocatingPriority.PRIORITY_ACCURACY,
     locatingTimeoutMs: timeoutMs
   };
   return await geoLocationManager.getCurrentLocation(request);
 } catch (error) {
   console.error(`单次定位失败: ${error.code}, ${error.message}`);
   return null;
 }
}

关键细节:

  • locatingPriority 决定定位策略:
  • PRIORITY_ACCURACY:优先保证精度,会返回一段时间内精度较好的结果,功耗较高。
  • PRIORITY_LOCATING_SPEED:优先保证速度,定位较快但精度可能略低。
  • locatingTimeoutMs 为超时时间(毫秒),超时后定位请求会失败。
  • 获取到的经纬度坐标为 WGS-84 坐标系。如需使用高德地图等国内地图服务,需要先转换为 GCJ-02 坐标系。
  • 单次定位通常需要数秒时间,建议在 UI 中显示加载状态。

五、逆地理编码:坐标转地址

获取到经纬度后,通过逆地理编码将坐标转换为用户可读的地址信息(省/市/区/街道等):

收起
自动换行
深色代码主题
复制
async getAddressFromLocation(latitude: number, longitude: number): 
 Promise<geoLocationManager.GeoAddress | null> {
 try {
   const request: geoLocationManager.ReverseGeoCodeRequest = {
     latitude: latitude,
     longitude: longitude,
     maxItems: 1,
     locale: 'zh_CN'
   };
   const addresses = await geoLocationManager.getAddressesFromLocation(request);
   return addresses && addresses.length > 0 ? addresses[0] : null;
 } catch (error) {
   console.error(`逆地理编码失败: ${error.code}, ${error.message}`);
   return null;
 }
}

关键细节:

  • 必须联网:逆地理编码需要访问后端服务,设备必须连接网络。
  • locale: 'zh_CN':指定返回中文地址信息。
  • maxItems: 1:只返回最匹配的一个地址。
  • 返回的 GeoAddress 对象包含以下常用属性:
  • administrativeArea:省份/直辖市/自治区
  • locality:城市
  • subLocality:区/县
  • roadName:道路名称
  • placeName:地点名称
  • 建议在调用前通过 isGeocoderAvailable() 检查逆地理编码服务是否可用。

六、持续定位:实时追踪位置

对于导航、运动轨迹、出行等需要持续获取位置变化的场景,使用 on('locationChange') 订阅持续定位:

收起
自动换行
深色代码主题
复制
startContinuousLocation(
 onLocationUpdate: (location: geoLocationManager.Location) => void,
 interval: number = 5,
 scenario: geoLocationManager.UserActivityScenario = 
   geoLocationManager.UserActivityScenario.NAVIGATION
): boolean {
 if (this.isListening) return false;
 
 this.locationCallback = onLocationUpdate;
 const request: geoLocationManager.ContinuousLocationRequest = {
   interval: interval,
   locationScenario: scenario
 };
 try {
   geoLocationManager.on('locationChange', request, this.locationCallback);
   this.isListening = true;
   return true;
 } catch (error) {
   console.error(`开启持续定位失败: ${error.code}, ${error.message}`);
   return false;
 }
}

停止持续定位:

收起
自动换行
深色代码主题
复制
stopContinuousLocation(): void {
 if (!this.isListening || !this.locationCallback) return;
 try {
   geoLocationManager.off('locationChange', this.locationCallback);
   this.isListening = false;
   this.locationCallback = undefined;
 } catch (error) {
   console.error(`停止持续定位失败: ${error.code}, ${error.message}`);
 }
}

关键细节:

  • interval:位置上报间隔(秒),值越小功耗越高。
  • locationScenario:定位场景,影响定位策略和功耗:
  • NAVIGATION:导航场景,室内外均可持续获取位置。
  • SPORT:运动场景。
  • TRANSPORT:交通出行场景。
  • 必须及时停止:在页面销毁或不需要定位时调用 off('locationChange') 取消订阅,释放资源并节省电量。
  • 持续定位会持续消耗电量,应根据实际场景合理设置上报间隔。

七、完整流程整合示例

将以上步骤整合到页面中,实现完整的定位与地址获取流程:

收起
自动换行
深色代码主题
复制
import { common } from '@kit.AbilityKit';
import { geoLocationManager } from '@kit.LocationKit';
import { LocationManager } from '../common/LocationManager';

@Entry
@Component
struct Index {
 private locationManager: LocationManager = new LocationManager();
 
 @State latitude: number = 0;
 @State longitude: number = 0;
 @State locationStatus: string = '未定位';
 @State address: string = '';

 onPageShow() {
   this.initLocation();
 }

 onPageHide() {
   // 页面隐藏时必须停止持续定位,节省电量
   this.locationManager.stopContinuousLocation();
 }

 async initLocation() {
   const context = getContext(this) as common.UIAbilityContext;

   // 步骤1:申请权限
   const granted = await this.locationManager.requestPermissions(context);
   if (!granted) {
     this.locationStatus = '权限被拒绝';
     return;
   }

   // 步骤2:检查位置开关
   if (!this.locationManager.isLocationEnabled()) {
     this.locationStatus = '请打开系统定位开关';
     return;
   }

   // 步骤3:优先获取缓存位置(省电)
   const cachedLocation = this.locationManager.getLastLocation();
   if (cachedLocation) {
     this.latitude = cachedLocation.latitude;
     this.longitude = cachedLocation.longitude;
     this.locationStatus = '已定位(缓存)';
   }

   // 步骤4:单次定位获取最新位置
   const location = await this.locationManager.getCurrentLocation(10000);
   if (location) {
     this.latitude = location.latitude;
     this.longitude = location.longitude;
     this.locationStatus = '已定位';

     // 步骤5:逆地理编码获取详细地址
     const geoAddress = await this.locationManager
       .getAddressFromLocation(this.latitude, this.longitude);
     if (geoAddress) {
       const province = geoAddress.administrativeArea || '';
       const city = geoAddress.locality || '';
       const district = geoAddress.subLocality || '';
       this.address = `${province}${city}${district}`.trim() || '地址未知';
     }
   } else {
     this.locationStatus = '定位失败';
   }
 }

 build() {
   // UI 构建代码...
 }
}

八、最佳实践总结

步骤 关键要点
权限配置 必须同时声明 APPROXIMATELY_LOCATION 和 LOCATION,先模糊后精确
位置开关检查 每次定位前调用 isLocationEnabled() 检查,引导用户开启
缓存位置优先 先取 getLastLocation(),可大幅节省功耗
单次定位 根据场景选择 PRIORITY_ACCURACY 或 PRIORITY_LOCATING_SPEED
逆地理编码 需联网,指定 locale: 'zh_CN' 返回中文地址
持续定位 必须在页面销毁时调用 off() 取消订阅,防止耗电
坐标系 LocationKit 返回 WGS-84 坐标,使用国内地图需转换
资源释放 每次定位请求完成后及时释放资源,避免内存泄漏

通过以上步骤,开发者可以在鸿蒙应用中完整实现从权限申请到获取详细地址的定位功能。LocationKit 提供的 geoLocationManager 模块能力丰富,合理运用缓存位置、单次定位和持续定位等不同方式,可以在精度和功耗之间取得最佳平衡,为用户带来流畅的定位体验。

收藏
3
回复
3
分享
全部评论
authorIcon
追光而行󰠇
学习了
回复于2026-07-16 12:35山东
authorIcon
初晨
可以
回复于2026-07-16 08:07江苏
authorIcon
寻常老百姓
学习
回复于2026-07-16 06:58甘肃
写评论
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。
发表
我要写文章
目录 收起
一、权限配置:声明与申请
1.1 配置文件声明权限
1.2 运行时动态申请权限
二、检查位置服务开关
三、获取缓存位置(省电优先)
四、单次定位:获取当前位置
五、逆地理编码:坐标转地址
六、持续定位:实时追踪位置
七、完整流程整合示例
八、最佳实践总结
了解社区公约,与您携手共创和谐专业的开发者社区。