Harmonyos5应用开发实战——地图组件集成与定位功能实现(part1)

Harmonyos5应用开发实战------地图组件集成与定位功能实现

文章内容概要

本文聚焦于HarmonyOS 5应用开发中地图组件集成与定位功能的实现。详细介绍了如何在应用中集成地图组件,获取用户定位权限,展示商家位置,并实现跳转到花瓣地图导航的功能。

核心功能介绍

1. 组件状态与属性初始化

在组件中定义了多个状态变量,用于存储地图相关信息,如经纬度、店铺信息、地图控制器等,并设置了地图的样式。

typescript 复制代码
@Component
export struct HwMap {
  @Consume('pageStack') pageStack: NavPathStack
  @State windowTopHeight: number = AppStorage.get('windowTopHeight') as number || 38.77
  @State latitude: number = 0
  @State longitude: number = 0
  @State storeInfo?: StoreInfo = undefined
  @State mapController?: map.MapComponentController | undefined = undefined;
  @State myLocation: geoLocationManager.Location | undefined = undefined;
  @State isShowMyLocation: boolean = false;
  private marker?: map.Marker;
  private mapOption?: mapCommon.MapOptions;
  private callback?: AsyncCallback<map.MapComponentController>;
  private style: mapCommon.MyLocationStyle = {
    anchorU: 0.5,
    anchorV: 0.5,
    radiusFillColor: 0xff00FFFFFF,
    displayType: mapCommon.MyLocationDisplayType.FOLLOW,
  };
}
2. 参数获取与权限请求

在组件即将显示时,通过getParams方法获取路由参数,得到店铺的经纬度和信息。同时,使用initPermission方法请求定位权限,若用户授权成功,则获取用户当前位置并在地图上显示。

typescript 复制代码
aboutToAppear(): void {
  this.getParams()
  this.initPermission()
  this.mapOption = {
    position: {
      target: {
        latitude: this.latitude,
        longitude: this.longitude,
      },
      zoom: 15,
    },
  };

  this.callback = async (err, mapController) => {
    if (!err) {
      this.mapController = mapController;
      this.mapController.on('mapLoad', () => {
        console.info('mapLoad success');
      });
      this.abilityEnabled();
      mapController.setMyLocationStyle(this.style);
      if (this.isShowMyLocation) {
        this.getLocation(this.mapController).then((location: geoLocationManager.Location) => {
          console.info('my location' + JSON.stringify(location));
          this.myLocation = location;
        });
      }
      // Marker初始化参数
      let markerOptions: mapCommon.MarkerOptions = {
        position: {
          latitude: this.latitude,
          longitude: this.longitude,
        },
        rotation: 0,
        visible: true,
        zIndex: 0,
        alpha: 1,
        anchorU: 0.5,
        anchorV: 1,
        clickable: true,
        draggable: true,
        flat: false,
      };
      // 创建Marker
      this.marker = await this.mapController.addMarker(markerOptions);
      await this.marker.setIcon($r('app.media.store_location'));
      this.mapController?.animateCamera(map.newLatLng({
        latitude: this.latitude,
        longitude: this.longitude,
      }, 15), 200);
    }
  };
}

getParams() {
  let paramsArr: HwMapModel[] = this.pageStack.getParamByName('HwMap') as HwMapModel[]
  if (paramsArr.length) {
    let routerParam = paramsArr[paramsArr.length-1]
    this.latitude = routerParam?.latitude ?? 0
    this.longitude = routerParam?.longitude ?? 0
    this.storeInfo = routerParam?.storeInfo ?? undefined
  }
}

initPermission() {
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

  atManager.requestPermissionsFromUser(getContext(this) as common.UIAbilityContext,
    ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
    .then((data) => {
      let grantStatus: Array<number> = data.authResults;
      // 用户授权,可以继续访问目标操作
      this.isShowMyLocation = grantStatus.every(item => item === Constants.USER_GRANT_SUCCESS)
      if (this.isShowMyLocation) {
        // 授权成功
        this.getLocation(this.mapController).then((location: geoLocationManager.Location) => {
          console.info('my location' + JSON.stringify(location));
          this.myLocation = location;
          this.mapController?.setMyLocationEnabled(true);
          this.mapController?.setMyLocationControlsEnabled(true);
          this.mapController?.setZoomControlsEnabled(false);
        });
      }

    }).catch((err: BusinessError) => {
      console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
    });
}
相关推荐
深海的鲸同学 luvi11 小时前
【HarmonyOS】个性化应用图标动态切换详解
华为·harmonyos
奔跑的露西ly13 小时前
【HarmonyOS NEXT】ohpm 安装依赖失败(@finclip 包找不到)问题复盘与解决方案
华为·harmonyos
余生H13 小时前
时光小铺鸿蒙商城上架全复盘 - 鸿蒙2025领航者闯关.成长升级路
华为·harmonyos·鸿蒙2025领航者闯关
鸭蛋超人不会飞14 小时前
鸿蒙OS学习与项目搭建报告
harmonyos
waeng_luo14 小时前
[鸿蒙2025领航者闯关]图标资源统一管理
harmonyos·鸿蒙2025领航者闯关·鸿蒙6实战·开发者年度总结
云上漫步者15 小时前
深度实战:Rust交叉编译适配OpenHarmony PC——unicode_width完整适配案例
开发语言·后端·rust·harmonyos
遇到困难睡大觉哈哈17 小时前
Harmony OS Web 组件:如何在新窗口中打开网页(实战分享)
前端·华为·harmonyos
赵财猫._.17 小时前
React Native鸿蒙开发实战(十):鸿蒙NEXT深度适配与未来展望
react native·react.js·harmonyos
2401_8603195217 小时前
在React Native鸿蒙跨平台开发采用分类网格布局,通过paramRow和paramLabel/paramValue的组合展示关键配置信息
react native·react.js·harmonyos
Archilect17 小时前
多阶段动效如何摆脱回调地狱:一个基于 ArkUI 的 AnimationStepper 设计
harmonyos