HarmonyOS Next应用开发实战——最优充电站页面实现(part1)

144 阅读1分钟

HarmonyOS Next应用开发实战——最优充电站页面实现

文章概要

本文聚焦于HarmonyOS Next应用开发中最优充电站页面的实现。详细介绍了该页面如何集成地图功能,包括地图的初始化、位置获取、地点搜索、标记点添加等操作,同时还实现了半模态框展示充电站列表,为用户提供了便捷的充电站选择体验。

核心功能介绍

1. 页面初始化与地图设置

在组件初始化时,设置地图的初始参数和回调函数,包括地图的中心点坐标、缩放级别等,并在地图加载完成后进行一系列操作。

@Entry
@Component
export struct OptimalStation {
  // ...
  build() {
    NavDestination() {
      Stack({ alignContent: Alignment.Bottom }) {
        MapComponent({ mapOptions: this.mapOption, mapCallback: this.callback }).width('100%').height('100%');
        // ...
      }
    }
    .hideTitleBar(true)
    .onReady(() => {
      // 地图初始化参数,设置地图中心点坐标及层级
      this.mapOption = {
        position: {
          target: this.latLng,
          zoom: 14
        },
        zoomControlsEnabled: false,
        myLocationControlsEnabled: true
      };

      // 地图初始化的回调
      this.callback = async (err, mapController) => {
        if (!err) {
          // 获取地图的控制器类,用来操作地图
          this.mapController = mapController;
          // 启用我的位置图层
          this.mapController?.setMyLocationEnabled(true);
          this.mapController.on('mapLoad', () => {
          });

          // 设置监听标记点击事件
          this.mapController.on('markerClick', (marker) => {
            this.queryLocation(marker.getTitle())
          });

          // 监听“我的位置”按钮点击事件
          this.mapController.on('myLocationButtonClick', () => {
            this.getMyLocation()
          });

          // 初始化我的位置
          this.getMyLocation()
        }
      };
    })
  }
}
2. 地点搜索功能

实现了文本搜索能力,用户输入地址后,通过调用 site.searchByText 方法进行搜索,并将结果在地图上进行标记和展示。

// 文本搜索能力
async searchByText() {
  let params: site.SearchByTextParams = {
    query: this.addressString,
    radius: 10000,
  };

  try {
    const result = await site.searchByText(params);
    if (result && result.sites && result.sites[0].location) {
      this.queryLocation(result.sites[0]?.siteId)
      this.mapCameraPosition(result.sites[0].location, result.sites[0].siteId)
    }
  } catch (err) {
    // ...
  }
}