产品服务
 400-0220-133
控制台
登录|免费试用

定位服务(harmony)

版本选择:

技术参数

定位SDK(harmony)

目录


环境要求

项目 要求
HarmonyOS NEXT 5.0+(API 15+)
DevEco Studio 6.0.2+
构建工具 hvigor 5.0.0+
包管理器 ohpm

SDK 部分方法要求 API 12+,已在各方法说明中标注。


集成步骤

1. 引入 HAR 包

将 ft_location_sdk.har 放入项目 libs/ 目录,在 entry/oh-package.json5 中添加依赖:

{
  "dependencies": {
    "ft_location_sdk": "file:./libs/ft_location_sdk.har"
  }
}

2. 同步依赖

ohpm install

3. 代码引入

import {
  FtLocationManager,
  FtGeoCoder,
  FtLocation,
  FtGeoAddress,
  FtLocationRequestPriority,
  FtLocationRequestScenario,
  FtLocatingPriority,
  // ...其他需要的类型
} from 'ft_location_sdk';

权限配置

SDK 内部已声明以下权限(ft_location_sdk/src/main/module.json5),接入方需在 entry/src/main/module.json5 中配置使用场景:

权限 说明 必填 授权方式
ohos.permission.LOCATION 精确位置 是 运行时弹窗申请
ohos.permission.APPROXIMATELY_LOCATION 粗略位置 是 随 LOCATION 一起授权
ohos.permission.LOCATION_IN_BACKGROUND 后台定位 按需(持续定位需声明) 设置 > 应用 > 权限 手动授予
ohos.permission.INTERNET 网络访问 是 自动授权(系统权限)

配置示例

// entry/src/main/module.json5
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:location_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "always"   // "always"=始终, "inuse"=仅前台
        }
      },
      {
        "name": "ohos.permission.APPROXIMATELY_LOCATION",
        "reason": "$string:location_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.LOCATION_IN_BACKGROUND",
        "reason": "$string:background_location_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "always"    // 仅后台/持续定位场景需要
        }
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "$string:internet_permission_reason",
        "usedScene": {
          "abilities": ["EntryAbility"],
          "when": "always"
        }
      }
    ]
  }
}

运行时权限申请

LOCATION 和 APPROXIMATELY_LOCATION 需要在运行时通过 abilityAccessCtrl 弹窗申请:

import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';

const PERMISSIONS: Array<Permissions> = [
  'ohos.permission.LOCATION' as Permissions,
  'ohos.permission.APPROXIMATELY_LOCATION' as Permissions,
];

const atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(context, PERMISSIONS).then((result) => {
  // result.authResults: Array<number>,0=已授权
});

LOCATION_IN_BACKGROUND 无法通过弹窗申请,需引导用户在「设置 > 应用 > 权限」中手动开启。

$string:location_reason 等需在 entry/src/main/resources/base/element/string.json 中定义,内容为用户可见的权限用途说明。


API 参考

所有方法均为 静态方法,无需实例化。

FtLocationManager - 定位管理器


getCurrentLocation()

单次定位(API 11+)

static async getCurrentLocation(
  request?: FtCurrentLocationRequest
): Promise<FtLocation>

参数

参数 类型 必填 默认值 说明
request FtCurrentLocationRequest 否 {} 定位请求配置

FtCurrentLocationRequest 字段:

字段 类型 必填 默认值 说明
priority FtLocationRequestPriority 否 — 定位优先级。ACCURACY 精度优先(GNSS 为主),LOW_POWER 低功耗(网络定位),FIRST_FIX 快速获取(GNSS+网络并行)
scenario FtLocationRequestScenario 否 — 定位场景,影响系统调度策略。NAVIGATION 导航、TRAJECTORY_TRACKING 轨迹记录、CAR_HAILING 打车、DAILY_LIFE_SERVICE 日常、NO_POWER 无功耗(跟随其他应用)
maxAccuracy number 否 — 最大允许精度误差,单位米。值越小精度要求越高,功耗越大
timeoutMs number 否 — 定位超时,单位毫秒。最小值 1000

返回值

Promise<FtLocation> — 位置信息对象,详见 FtLocation。

异常

定位失败时抛出异常,建议使用 try-catch。常见错误:定位服务未开启、权限未授予、超时。

示例

try {
  const request: FtCurrentLocationRequest = {
    priority: FtLocationRequestPriority.ACCURACY,
    scenario: FtLocationRequestScenario.DAILY_LIFE_SERVICE,
    timeoutMs: 10000,
  };
  const location: FtLocation = await FtLocationManager.getCurrentLocation(request);
  console.log(`位置: ${location.latitude}, ${location.longitude}`);
  console.log(`精度: ${location.accuracy}m`);
} catch (err) {
  console.error('定位失败:', err);
}

getCurrentLocationV2()

单次定位(API 12+)

使用简化的 SingleLocationRequest 参数结构,仅需设置优先级和超时。

static async getCurrentLocationV2(
  request: FtSingleLocationRequest
): Promise<FtLocation>

参数

参数 类型 必填 说明
request FtSingleLocationRequest 是 定位请求配置

FtSingleLocationRequest 字段:

字段 类型 必填 说明
locatingPriority FtLocatingPriority 是 定位优先级。PRIORITY_ACCURACY 精度优先,PRIORITY_LOCATING_SPEED 速度优先
locatingTimeoutMs number 是 定位超时,单位毫秒。最小值 1000

返回值

Promise<FtLocation> — 同 getCurrentLocation()。

示例

const request: FtSingleLocationRequest = {
  locatingPriority: FtLocatingPriority.PRIORITY_ACCURACY,
  locatingTimeoutMs: 10000,
};
const location = await FtLocationManager.getCurrentLocationV2(request);

getLastLocation()

获取缓存位置(同步)

返回系统最近一次定位缓存结果。无缓存或定位服务关闭时返回 null。

static getLastLocation(): FtLocation | null

参数

无。

返回值

FtLocation | null — 缓存位置,无缓存返回 null。

示例

const location = FtLocationManager.getLastLocation();
if (location !== null) {
  console.log(`缓存位置: ${location.latitude}, ${location.longitude}`);
} else {
  console.log('无缓存位置');
}

isLocationEnabled()

检查定位开关状态(同步)

static isLocationEnabled(): boolean

参数

无。

返回值

boolean — true 表示系统定位服务已开启,false 表示已关闭。

示例

if (!FtLocationManager.isLocationEnabled()) {
  // 引导用户开启定位
}

watchLocationChange()

持续定位监听(API 11+)

注册位置变化监听,返回取消函数。支持按时间间隔和距离间隔过滤上报。

static watchLocationChange(
  request: FtLocationRequest,
  callback: FtLocationCallback
): () => void

参数

参数 类型 必填 说明
request FtLocationRequest 是 持续定位请求配置
callback FtLocationCallback 是 位置变化回调,参数为 FtLocation

FtLocationRequest 字段:

字段 类型 必填 默认值 说明
priority FtLocationRequestPriority 是 — 定位优先级
scenario FtLocationRequestScenario 否 UNSET 定位场景
timeInterval number 否 1 位置上报时间间隔,单位秒。需 > 0 才生效
distanceInterval number 否 0 位置上报距离间隔,单位米。需 > 0 才生效
maxAccuracy number 否 0 最大精度,单位米

返回值

() => void — 取消函数。调用后停止监听。

示例

const request: FtLocationRequest = {
  priority: FtLocationRequestPriority.ACCURACY,
  scenario: FtLocationRequestScenario.NAVIGATION,
  timeInterval: 1,         // 每秒上报
  distanceInterval: 0,     // 不限制距离
};

// 开始监听
const stopWatch = FtLocationManager.watchLocationChange(
  request,
  (location: FtLocation): void => {
    console.log(`位置更新: ${location.latitude}, ${location.longitude}`);
  }
);

// 停止监听(不再需要时调用)
stopWatch();

watchContinuousLocationChange()

持续定位监听(API 12+)

使用 ContinuousLocationRequest 参数结构,支持活动场景与功耗场景联合设置。

static watchContinuousLocationChange(
  request: FtContinuousLocationRequest,
  callback: FtLocationCallback
): () => void

参数

参数 类型 必填 说明
request FtContinuousLocationRequest 是 持续定位请求配置
callback FtLocationCallback 是 位置变化回调

FtContinuousLocationRequest 字段:

字段 类型 必填 说明
interval number 是 位置上报时间间隔,单位秒
locationScenario FtUserActivityScenario | FtPowerConsumptionScenario 是 场景设置。可传活动场景(NAVIGATION/SPORT/TRANSPORT/DAILY_LIFE_SERVICE)或功耗场景(HIGH_POWER_CONSUMPTION/LOW_POWER_CONSUMPTION/NO_POWER_CONSUMPTION)

返回值

() => void — 取消函数。

示例

const request: FtContinuousLocationRequest = {
  interval: 2,
  locationScenario: FtUserActivityScenario.SPORT,
};

const stopWatch = FtLocationManager.watchContinuousLocationChange(
  request,
  (location: FtLocation): void => {
    console.log(`运动定位: ${location.latitude}, ${location.longitude}`);
  }
);

// 停止
stopWatch();

onLocationEnabledChange() / offLocationEnabledChange()

定位开关状态变化监听

系统定位服务开启或关闭时触发回调。

// 注册监听
static onLocationEnabledChange(callback: FtLocationEnabledChangeCallback): void

// 取消监听
static offLocationEnabledChange(callback?: FtLocationEnabledChangeCallback): void

参数

参数 类型 必填 说明
callback FtLocationEnabledChangeCallback 是(注册时) 回调函数,参数 isEnabled: boolean,true 为开启
callback FtLocationEnabledChangeCallback 否(取消时) 传具体回调引用则只取消该回调;不传则取消所有监听

示例

// 保存回调引用以便后续取消
const onEnabledChange = (isEnabled: boolean): void => {
  console.log(`定位服务${isEnabled ? '已开启' : '已关闭'}`);
};

// 注册
FtLocationManager.onLocationEnabledChange(onEnabledChange);

// 取消(传入相同引用)
FtLocationManager.offLocationEnabledChange(onEnabledChange);

onLocationError() / offLocationError()

定位错误监听(API 12+)

定位过程中发生错误时触发回调。

// 注册监听
static onLocationError(callback: FtLocationErrorCallback): void

// 取消所有监听(无参数)
static offLocationError(): void

参数

参数 类型 说明
callback FtLocationErrorCallback 回调函数,参数 err: number 为错误码

示例

FtLocationManager.onLocationError((errCode: number): void => {
  console.error('定位错误,错误码:', errCode);
});

// 取消所有错误监听
FtLocationManager.offLocationError();

FtRGeoService - RGeo 逆地理编码


reverseGeoCode()

逆地理编码(经纬度 → 详细地址),调用丰图远程 RGeo 接口。

static async reverseGeoCode(
  request: FtRGeoRequest
): Promise<FtRGeoResult>

参数

参数 类型 必填 说明
request FtRGeoRequest 是 RGeo 请求

FtRGeoRequest 字段:

字段 类型 必填 默认值 说明
longitude number 是 — 经度
latitude number 是 — 纬度
coordinateSystem string 否 '1' 坐标系:'1'=GCJ-02(高德),'2'=BD-09(百度)
fill number 否 0 行政区划名称补全开关,=1 时补全缺少的省/市/区名称

返回值

Promise<FtRGeoResult> — 地址结果,详见 FtRGeoResult。

示例

const request: FtRGeoRequest = {
  longitude: 116.4074,
  latitude: 39.9042,
  coordinateSystem: '1',
  fill: 1,
};
const result = await FtRGeoService.reverseGeoCode(request);
console.log(`位置: ${result.name}`);
console.log(`省市区: ${result.province} ${result.city} ${result.district}`);

类型定义

枚举

FtLocationRequestPriority

定位请求优先级(API 11+),用于 FtCurrentLocationRequest.priority 和 FtLocationRequest.priority。

枚举值 数值 说明
UNSET 0x200 未设置,优先级字段不生效
ACCURACY 0x201 精度优先:以 GNSS 定位为主,功耗较高
LOW_POWER 0x202 低功耗优先:使用网络定位,精度较低
FIRST_FIX 0x203 快速获取:同时使用 GNSS 和网络定位,返回最先获取的结果

FtLocationRequestScenario

定位请求场景(API 11+),用于 FtCurrentLocationRequest.scenario 和 FtLocationRequest.scenario。

枚举值 数值 说明
UNSET 0x300 未设置,字段无效
NAVIGATION 0x301 导航场景:车载/骑行导航,精度较高
TRAJECTORY_TRACKING 0x302 运动轨迹记录
CAR_HAILING 0x303 打车场景
DAILY_LIFE_SERVICE 0x304 日常使用:不要求精确定位
NO_POWER 0x305 无功耗:仅在其他应用定位时跟随获取

FtUserActivityScenario

用户活动场景(API 12+),用于 FtContinuousLocationRequest.locationScenario。

枚举值 数值 说明
NAVIGATION 0x401 导航
SPORT 0x402 运动
TRANSPORT 0x403 出行(公交/地铁/打车)
DAILY_LIFE_SERVICE 0x404 日常使用

FtPowerConsumptionScenario

功耗场景(API 12+),用于 FtContinuousLocationRequest.locationScenario。可与 FtUserActivityScenario 联合使用。

枚举值 数值 说明
HIGH_POWER_CONSUMPTION 0x601 高功耗:以 GNSS 为主
LOW_POWER_CONSUMPTION 0x602 低功耗:使用网络定位
NO_POWER_CONSUMPTION 0x603 无功耗:跟随其他应用

FtLocatingPriority

定位优先级(API 12+),用于 FtSingleLocationRequest.locatingPriority。

枚举值 数值 说明
PRIORITY_ACCURACY 0x501 精度优先:GNSS+网络并行,返回精度较好的结果
PRIORITY_LOCATING_SPEED 0x502 速度优先:GNSS+网络并行,返回最先获取的结果

FtLocationSourceType

定位源类型(API 12+),出现在 FtLocation.sourceType 返回值中。

枚举值 数值 说明
GNSS 1 GNSS 卫星定位
NETWORK 2 网络定位(基站/WLAN/蓝牙)
INDOOR 3 室内高精度定位
RTK 4 RTK 高精度定位

数据接口

FtLocation

位置信息,所有定位方法的返回值。

字段 类型 必填 说明
latitude number 是 纬度,-90 ~ 90,WGS84 坐标系
longitude number 是 经度,-180 ~ 180,WGS84 坐标系
altitude number 是 海拔,单位米
accuracy number 是 精度,单位米。值越小精度越高
speed number 是 速度,单位米/秒
timeStamp number 是 位置时间戳,UTC 毫秒
direction number 是 方向,单位度,0 ~ 360。0=正北,90=正东
timeSinceBoot number 是 位置时间,以开机时间为基准的纳秒数
additions Array<string> 是 附加信息数组
additionSize number 是 附加信息数量
additionsMap Map<string, string> 否 附加信息键值对(API 12+),顺序与 additions 一致
altitudeAccuracy number 否 海拔精度,单位米(API 12+)
speedAccuracy number 否 速度精度,单位米/秒(API 12+)
directionAccuracy number 否 方向精度,单位度(API 12+)
uncertaintyOfTimeSinceBoot number 否 位置时间不确定度,纳秒(API 12+)
sourceType FtLocationSourceType 否 定位源类型(API 12+)

请求接口

接口 用途 用于方法
FtCurrentLocationRequest 单次定位请求(API 11+) getCurrentLocation()
FtSingleLocationRequest 单次定位请求(API 12+) getCurrentLocationV2()
FtLocationRequest 持续定位请求(API 11+) watchLocationChange()
FtContinuousLocationRequest 持续定位请求(API 12+) watchContinuousLocationChange()
FtRGeoRequest RGeo 逆地理编码请求 FtRGeoService.reverseGeoCode()

RGeo 数据接口

接口 用途
FtRGeoResult RGeo 查询结果(name、province、city、district)

各接口字段详见对应方法说明中的参数表。


回调类型

类型 签名 用途
FtLocationCallback (location: FtLocation) => void 位置变化回调
FtLocationEnabledChangeCallback (isEnabled: boolean) => void 定位开关变化回调
FtLocationErrorCallback (err: number) => void 定位错误回调,参数为错误码

错误码说明

所有 SDK 异步方法在失败时抛出 FtAuthError(继承自 Error),包含 code(错误码)、message(描述)和 reqId(请求 ID)三个属性。

SDK 验证错误码

错误码 说明 处理建议
-2 appId 自动获取失败 检查应用签名配置,确认 bundleManager.getBundleInfoForSelfSync() 可正常返回
-1 网络异常(超时 / DNS / 连接失败) 检查网络连接,确认设备可访问验证域名
401 AK 格式不正确 检查 AK 码是否正确,确认无多余空格或字符
403 AK 未授权 确认 AK 码正确且已在开放平台绑定当前应用
429 AK 额度不足,请求被限流 升级配额或降低调用频率
3001 不支持的平台类型 SDK 内部错误,请联系技术支持
3002 未找到对应的验证信息 确认 AK 码正确且已激活

RGeo 服务错误码

错误码 说明 处理建议
3003 地址解析无法返回结果 检查经纬度是否在有效范围内
3004 请求服务超时 检查网络状况后重试
3005 请求服务异常 服务端临时故障,稍后重试
3006 调用服务响应 data 不存在 服务端返回格式异常,请联系技术支持

系统定位错误码

通过 FtLocationManager.onLocationError() 回调获取,参数为系统 LocationError 枚举值:

错误码 枚举名 说明
1 LOCATION_ERROR_SWITCH_OFF 定位开关关闭
2 LOCATION_ERROR_NO_NETWORK 无网络连接
3 LOCATION_ERROR_PERMISSION_DENIED 未授予定位权限
4 LOCATION_ERROR_GEO_CONVERTER_UNAVAILABLE 地理编码服务不可用

错误处理示例

import { FtAuthError } from 'ft_location_sdk';

try {
  const location = await FtLocationManager.getCurrentLocation(request);
} catch (err) {
  if (err instanceof FtAuthError) {
    const authErr = err as FtAuthError;
    console.error(`错误 [${authErr.code}]: ${authErr.message}`);
    if (authErr.code === 401) {
      // AK 格式不正确,提示用户检查
    } else if (authErr.code === 403) {
      // AK 未授权,提示用户检查配置
    } else if (authErr.code === 429) {
      // 被限流,延迟重试
    }
  } else if (err instanceof Error) {
    console.error(`系统错误: ${err.message}`);
  }
}

完整示例

import {
  FtLocationManager,
  FtRGeoService,
  FtLocation,
  FtLocationRequestPriority,
  FtLocationRequestScenario,
  FtCurrentLocationRequest,
  FtLocationRequest,
  FtLocationEnabledChangeCallback,
  FtRGeoRequest,
  FtRGeoResult,
} from 'ft_location_sdk';

// 0. 初始化 SDK(必须先调用)
FtLocationManager.init({ ak: 'your_ak_here', isProd: true });

// 1. 检查定位开关
if (!FtLocationManager.isLocationEnabled()) {
  console.log('请先开启定位服务');
}

// 2. 单次定位
const locationReq: FtCurrentLocationRequest = {
  priority: FtLocationRequestPriority.ACCURACY,
  scenario: FtLocationRequestScenario.DAILY_LIFE_SERVICE,
  timeoutMs: 10000,
};
const location = await FtLocationManager.getCurrentLocation(locationReq);
console.log(`位置: ${location.latitude}, ${location.longitude}, 精度: ${location.accuracy}m`);

// 3. 持续定位
const watchReq: FtLocationRequest = {
  priority: FtLocationRequestPriority.ACCURACY,
  timeInterval: 1,
  distanceInterval: 5,   // 每 5 米或每 1 秒上报
};
const stopWatch = await FtLocationManager.watchLocationChange(
  watchReq,
  (loc: FtLocation) => {
    console.log(`持续定位: ${loc.latitude}, ${loc.longitude}`);
  }
);
// 不再需要时停止
stopWatch();

// 4. 监听定位开关变化
const enabledCb: FtLocationEnabledChangeCallback = (isEnabled: boolean) => {
  console.log(`定位服务${isEnabled ? '开启' : '关闭'}`);
};
FtLocationManager.onLocationEnabledChange(enabledCb);
// 取消监听
FtLocationManager.offLocationEnabledChange(enabledCb);

// 5. RGeo 逆地理编码(远程服务)
const rgeoReq: FtRGeoRequest = {
  longitude: 116.4074,
  latitude: 39.9042,
  coordinateSystem: '1',
  fill: 1,
};
const rgeoResult: FtRGeoResult = await FtRGeoService.reverseGeoCode(rgeoReq);
console.log(`${rgeoResult.province}${rgeoResult.city}${rgeoResult.district} - ${rgeoResult.name}`);

构建与发布

构建 HAR 包

DEVECO_SDK_HOME="<DevEco SDK 路径>" \
  hvigorw assembleHap -p product=default

发布

SDK 产出物为 ft_location_sdk/build/default/outputs/default/ft_location_sdk.har,将此文件提供给接入方即可。

项目结构

FtLocationSDK/
├── ft_location_sdk/              # HAR 模块(SDK 本体)
│   ├── src/main/ets/
│   │   ├── Index.ets             # 导出入口
│   │   ├── FtLocationManager.ets # 定位管理器
│   │   ├── FtRGeoService.ets     # RGeo 逆地理编码(远程服务)
│   │   ├── auth/                 # FtAuthVerifier + FtAuthError
│   │   └── types/
│   │       └── FtLocationTypes.ets  # 所有枚举、接口、回调类型
│   ├── src/main/module.json5     # HAR 权限声明
│   └── oh-package.json5
└── entry/                        # Demo 应用(验证用,不发布)
    ├── src/main/ets/
    │   ├── entryability/EntryAbility.ets
    │   └── pages/Index.ets       # 完整 API 调用示例(Tab 分区)
    └── src/main/module.json5     # 需配置权限 usedScene

下载 定位SDK(鸿蒙)

联系电话400-0220-133
联系电话联系电话
在线客服联系在线客服
在线客服在线客服
售前咨询
售前咨询售前咨询
拨号
拨号拨号