HarmonyOS Next深度解析:高德定位SDK高效集成与实战指南

发布于:2025-06-19 ⋅ 阅读:(18) ⋅ 点赞:(0)

HarmoyOS Next 实现高德定位SDK

注:作者采用版本为 HarmonyOS 5.0.0 Release SDK和DevEco Studio 5.0.0 Release。

1.获取本地AppID:

  • 在index.pages的abountToAppear( ) 方法中获取appID、并打印在Log日志,即可在程序运行时获取本地项目的AppID。
    在这里插入图片描述

2. 申请高德定位SDK的key:

  • 高德地图API
  • 输入本地的AppID即可申请获取到高德定位SDK的Key
  • 在这里插入图片描述

3. 配置权限声明:在项目的module.json5配置相关权限,以及配置相关权限reason。

  • 其中 reason 可以在string.json中自行命名。
"requestPermissions": [
      {
        "name": "ohos.permission.APPROXIMATELY_LOCATION",
        "reason": "$string:Harmony_location_permission_reason",
        "usedScene": {
          "abilities": [
            "Harmony_location_demoAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.LOCATION",
        "reason": "$string:Harmony_location_permission_reason",
        "usedScene": {
          "abilities": [
            "Harmony_location_demoAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.LOCATION_IN_BACKGROUND",
          "reason": "$string:Harmony_location_permission_reason",
        "usedScene": {
          "abilities": [
            "Harmony_location_demoAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "$string:Harmony_location_permission_reason",
        "usedScene": {
          "abilities": [
            "Harmony_location_demoAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING",
        "reason": "$string:Harmony_location_permission_reason",
        "usedScene": {
          "abilities": [
            "Harmony_location_demoAbility"
          ],
          "when": "always"
        }
      }
    ]

4. oh-package.json5 中获取相关定位包:

"dependencies": {
    "@amap/amap_lbs_common": ">=1.2.0",
    "@amap/amap_lbs_location": ">=1.2.0"
  }

5. 初始化隐私政策,创建AMapLocationManagerImpl,以及动态生成权限。

  • 导入所需模块
import { AMapLocation, AMapLocationManagerImpl } from '@amap/amap_lbs_location';
import { AMapPrivacyAgreeStatus, AMapPrivacyInfoStatus, AMapPrivacyShowStatus } from '@amap/amap_lbs_common';
import { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl, { PermissionRequestResult } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import { AMapLocationOption, AMapLocationReGeocodeLanguage, AMapLocationType, IAMapLocationListener } from '@amap/amap_lbs_location';
import geoLocationManager from '@ohos.geoLocationManager';
import { promptAction } from '@kit.ArkUI';
  • 初始化隐私政策,创建AMapLocationManagerImpl及动态申请权限
locationManger?: AMapLocationManagerImpl;
  private context = getContext(this);


  onPageShow() {
    //设置Key
    AMapLocationManagerImpl.setApiKey("**高德定位SDK的key**");

    //初始化隐私政策
    AMapLocationManagerImpl.updatePrivacyShow(AMapPrivacyShowStatus.DidShow, AMapPrivacyInfoStatus.DidContain, getContext(this))
    AMapLocationManagerImpl.updatePrivacyAgree(AMapPrivacyAgreeStatus.DidAgree, getContext(this))

    //创建AMapLocationManagerImpl
    this.locationManger = new AMapLocationManagerImpl(this.context);

    // 检查系统定位是否开启
    checkLocationEnabled();
    //获取权限
    this.reqPermissionsFromUser([
      'ohos.permission.APPROXIMATELY_LOCATION',
      'ohos.permission.LOCATION',
    ]);
  }
  // 请求权限
  reqPermissionsFromUser(permissions: Array<Permissions>): void {
    let context: Context = getContext(this) as common.UIAbilityContext;
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(context, permissions).then((data: PermissionRequestResult) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权,可以继续访问目标操作
          this.message = '权限已授权';
        } else {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
          this.message = '需要定位权限,请前往设置开启';
          // 弹出 Toast 提示
          promptAction.showToast({
            message: '需要定位权限,请前往设置开启',
            duration: 3000
          });
          return;
        }
      }
      // 授权成功
    }).catch((err: BusinessError) => {
      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
    })
  }

  • 在struct 界面结构体外配置异步方法,用于检查定位是否启用。
// 检查定位是否启用
async function checkLocationEnabled() {
  try {
    let isEnabled = await geoLocationManager.isLocationEnabled();
    console.info("Location is enabled: " + isEnabled);
  } catch (error) {
    console.error("Failed to check location status: " + JSON.stringify(error));
  }
}

6. 开启单次定位参数配置(也可自行配置为连续定位)

// 定位配置项
  options: AMapLocationOption = {
    priority: geoLocationManager.LocationRequestPriority.FIRST_FIX, //定位优先配置选项
    scenario: geoLocationManager.LocationRequestScenario.UNSET, //定位场景设置
    timeInterval: 2, //定位时间间隔
    distanceInterval: 0, //位置报告距离间隔
    maxAccuracy: 20, //定位精度 单位:米
    allowsBackgroundLocationUpdates: false, //是否允许后台定位
    locatingWithReGeocode: true, //定位是否返回逆地理信息
    reGeocodeLanguage: AMapLocationReGeocodeLanguage.Chinese, //逆地址语言类型
    isOffset: true //是否加偏
  }
  • 补充目前高德定位SDK的逆地理信息未适配HarmonyOS Next,可采用高德Web服务,进行经纬度逆向转换为具体的地理信息。
  • 定位信息监听配置及经纬度信息解析:
// 定位监听器
  listener: IAMapLocationListener = {
    onLocationChanged: (location) => {
      this.response = "\n"
        + " 经度:" + location.longitude + "\n"
        + " 纬度:" + location.latitude + "\n"
        + " 海拔:" + location.altitude + "\n"
        + " 精度:" + location.accuracy + "\n"
        + " 速度:" + location.speed + "\n"
        + " UTC时间:" + location.timeStamp + "\n"
        + " 方向:" + location.direction + "\n"
        + " 自启动以来时间:" + location.timeSinceBoot + "\n"
        + " 附加信息:" + location.additions + "\n"
        + " 附加信息size:" + location.additionSize + "\n"
        + " 逆地理:" + location.reGeo?.country
    }, onLocationError: (error) => {
      this.response = JSON.stringify(error);
      // todo something
    }
  };

7. 定位功能调用及关闭

    @State response: string = '';
    ---
	Row(){
        Button('开始定位')
          .fontSize(20)
          .margin(20)
          .onClick(() => {
            this.locationManger?.setLocationListener(AMapLocationType.Updating, this.listener) //设置定位信息监听
            this.locationManger?.setLocationOption(AMapLocationType.Updating, this.options) //设置定位配置项
            this.locationManger?.startUpdatingLocation() //开启连续定位

            // this.locationManger?.stopUpdatingLocation() //关闭连续定位
          })
        Button('停止定位')
          .fontSize(20)
          .margin(20)
          .onClick(() => {
            this.locationManger?.stopUpdatingLocation() //关闭连续定位
          })
      }

      Text("具体地址信息:" + this.response).fontSize(20)
      

8.具体效果如图:
在这里插入图片描述
9. 使用时不要忘记右键下拉,开启手机的定位服务。
10.错误码说明:在这里插入图片描述

  • 总结:
    以上为如何在HarmonyOS Next 5.0 使用高德定位SDK的模块;
    如有任何问题,请大家指出,本人再进行完善

网站公告

今日签到

点亮在社区的每一天
去签到