HarmonyOS Next应用开发实战——服务页面功能实现(part1)

91 阅读2分钟

HarmonyOS Next应用开发实战——服务页面功能实现

文章概要

本文聚焦于HarmonyOS Next应用开发中服务页面的实现。详细介绍了服务页面的布局搭建、地图功能集成、权限检查、扫码功能以及页面跳转逻辑,通过调用多个Kit实现了多样化的服务功能,为用户提供了便捷的交互体验。

核心功能介绍

1. 权限检查与地图初始化

在组件即将显示时,首先检查定位相关权限,然后初始化地图组件。

aboutToAppear(): void {
  PermissionsUtil.checkPermissions(this.permissions)
  // 地图初始化参数,设置地图中心点坐标及层级
  this.mapOption = {
    position: {
      target: this.latLng,
      zoom: this.zoom
    },
    // 是否支持滑动手势,默认值为true
    scrollGesturesEnabled: false,
    // 是否展示缩放控件,默认值为true
    zoomControlsEnabled: false,
    // 是否展示定位按钮,默认值为false
    myLocationControlsEnabled: false,
    // 是否展示指南针控件,默认值为true
    compassControlsEnabled: false,
    // 是否展示比例尺,默认值为false
    scaleControlsEnabled: true
  };
  // 地图初始化的回调
  this.callback = async (err, mapController) => {
    if (!err) {
      // 获取地图的控制器类,用来操作地图
      this.mapController = mapController;
      // 启用我的位置图层
      this.mapController?.setMyLocationEnabled(true);
      // 隐藏我的位置按钮
      this.mapController?.setMyLocationControlsEnabled(false);
      this.mapController.on('mapLoad', () => {
      });
      this.mapController.on('mapClick', (position) => {
        this.pageInfos.pushPath({ name: 'OptimalStation' })
      });

      // 初始化我的位置
      this.getMyLocation()
    }
  };
}
2. 获取当前位置并移动地图视图

通过geoLocationManager获取当前位置,将其转换为GCJ02坐标后,移动地图相机到该位置。

// 获取当前位置并视图移动过去
getMyLocation() {
  geoLocationManager.getCurrentLocation().then(async (result) => {
    let position: geoLocationManager.Location = {
      'latitude': result.latitude,
      'longitude': result.longitude,
      'altitude': 0,
      'accuracy': 0,
      'speed': 0,
      'timeStamp': 0,
      'direction': 0,
      'timeSinceBoot': 0,
      altitudeAccuracy: 0,
      speedAccuracy: 0,
      directionAccuracy: 0,
      uncertaintyOfTimeSinceBoot: 0,
      sourceType: geoLocationManager.LocationSourceType.GNSS
    };
    this.mapController?.setMyLocation(position);
    // 创建CameraUpdate对象
    let gcj02Posion: mapCommon.LatLng = await this.convertCoordinate(result.latitude, result.longitude)
    let latLng: mapCommon.LatLng = {
      latitude: gcj02Posion.latitude,
      longitude: gcj02Posion.longitude
    };
    let cameraUpdate = map.newLatLng(latLng, this.zoom);
    // 以非动画方式移动地图相机
    this.mapController?.moveCamera(cameraUpdate);
    // 以动画方式移动地图相机
  })
}

async convertCoordinate(latitude: number, longitude: number): Promise<mapCommon.LatLng> {
  let wgs84Position: mapCommon.LatLng = {
    latitude: latitude,
    longitude: longitude
  };
  let gcj02Posion: mapCommon.LatLng =
    await map.convertCoordinate(mapCommon.CoordinateType.WGS84, mapCommon.CoordinateType.GCJ02, wgs84Position);

  return gcj02Posion;
}