乐于分享
好东西不私藏

鸿蒙Flutter插件精选:geolocator_ohos

鸿蒙Flutter插件精选:geolocator_ohos

geolocator_ohos 是 geolocator[1] 在 OpenHarmony(鸿蒙)平台的实现,为鸿蒙设备提供定位、地理编码等位置服务能力。

插件介绍

geolocator_ohos 是 geolocator 的鸿蒙平台适配插件,提供与标准 geolocator API 一致的定位能力,同时额外支持鸿蒙特有的地理编码/逆地理编码功能。

  • 版本: ^0.0.3
  • 平台: OpenHarmony / HarmonyOS
  • 依赖关系: geolocator: 14.0.2^ geolocator_ohos: 0.0.3^

安装

在 pubspec.yaml 中添加依赖:

dependencies:
  geolocator: 
14.0.2^geolocator_ohos:0.0.3^

然后在项目的 module.json5 中配置定位权限:

"requestPermissions": [
  {"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"},
  {
    "name": "ohos.permission.LOCATION",
    "reason": "$string:EntryAbility_label",
    "usedScene": {
      "abilities": ["EntryAbility"],
      "when": "inuse"
    }
  },
  {
    "name": "ohos.permission.APPROXIMATELY_LOCATION",
    "reason": "$string:EntryAbility_label",
    "usedScene": {
      "abilities": ["EntryAbility"],
      "when": "inuse"
    }
  },
  {
    "name": "ohos.permission.LOCATION_IN_BACKGROUND",
    "reason": "$string:EntryAbility_label",
    "usedScene": {
      "abilities": ["EntryAbility"],
      "when": "inuse"
    }
  }
]

使用

获取国家码

CountryCode? countryCode = await geolocatorOhos.getCountryCode();

获取当前位置

final position = await geolocatorOhos.getCurrentPosition(
  locationSettings: const CurrentLocationSettingsOhos(
    priority: LocationRequestPriority.firstFix,
    scenario: LocationRequestScenario.unset,
  ),
);

逆地理编码(地址解析)

if (await geolocatorOhos.isGeocoderAvailable()) {
  var addresses = await geolocatorOhos.getAddressesFromLocation(
    ReverseGeoCodeRequest(
      latitude: position.latitude,
      longitude: position.longitude,
      locale: 'zh',
      maxItems: 1,
    ),
  );
}

地理编码(地址→坐标)

var position = await geolocatorOhos.getAddressesFromLocationName(
  GeoCodeRequest(description: address.placeName ?? ''),
);

以上就是 geolocator_ohos 的核心用法,代码简洁明了,几行即可为鸿蒙应用接入定位能力 🚀

更详细的使用方式可以参考 geolocator_ohos[2] 或 geolocator[3] 官方文档。

--------------------------

由我编著的《鸿蒙Flutter开发实战》图书已上架京东图书等各大商店,内容涵盖基础知识、鸿蒙化原理及适配、混合开发、插件开发、高级特性优化、性能分析、三方库适配、开发实战、鸿蒙PC等等,基于 Flutter 3.35 版本,是不可多得的 Flutter鸿蒙化适配工具书和实战案例,欢迎大家选购 🎉🎉🎉

引用链接

[1]geolocator: https://pub.flutter-io.cn/packages/geolocator

[2]geolocator_ohos: https://pub.flutter-io.cn/packages/geolocator_ohos

[3]geolocator: https://pub.flutter-io.cn/packages/geolocator

相关学习资料