MapKit地图组件集成

鸿蒙原生开发手记:徒步迹 - MapKit 地图组件集成

集成鸿蒙地图服务,实现路线展示和位置定位


一、前言

地图是徒步 App 的核心功能。鸿蒙提供了 MapKit 地图组件,支持地图展示、标记、路线绘制、定位等功能。


二、准备工作

2.1 申请 API Key

在华为开发者联盟 -> App Services -> 地图服务 中申请 API Key。

2.2 配置权限

// module.json5
{
  "requestPermissions": [
    {
      "name": "ohos.permission.LOCATION",
      "reason": "用于记录徒步轨迹和显示当前位置"
    },
    {
      "name": "ohos.permission.APPROXIMATELY_LOCATION",
      "reason": "用于记录徒步轨迹和显示当前位置"
    },
    {
      "name": "ohos.permission.INTERNET",
      "reason": "加载地图数据"
    }
  ]
}

2.3 配置 API Key

// build-profile.json5
{
  "app": {
    "hms": {
      "apiKey": "your_api_key_here"
    }
  }
}

三、基础地图组件

3.1 显示地图

import { MapComponent, MapOptions, MapView } from '@kit.MapKit';

@Entry
@Component
struct MapPage {
  private mapOptions: MapOptions = {
    center: {        // 初始中心点
      lat: 39.908,
      lng: 116.397,
    },
    zoom: 15,        // 缩放级别
    tilt: 0,         // 倾斜角度
  };

  build() {
    Column() {
      // 地图组件
      MapComponent({
        mapOptions: this.mapOptions,
        onMapReady: (map: MapView) => {
          console.log('地图加载完成');
        },
      })
      .width('100%')
      .height('100%');
    }
  }
}

3.2 添加标记

onMapReady(map: MapView): void {
  // 添加标记
  map.addMarker({
    position: { lat: 39.908, lng: 116.397 },
    title: '当前位置',
    snippet: '徒步起点',
    icon: 'marker_icon',              // 自定义图标
    draggable: false,
  });

  // 批量添加标记
  map.addMarkers([
    {
      position: { lat: 39.910, lng: 116.400 },
      title: '观景台',
    },
    {
      position: { lat: 39.915, lng: 116.405 },
      title: '山顶',
    },
  ]);
}

四、路线绘制

4.1 绘制轨迹线

function drawPolyline(map: MapView, points: Coordinate[]): void {
  // 将坐标点转换为地图坐标
  const path = points.map(p => ({
    lat: p.latitude,
    lng: p.longitude,
  }));

  // 绘制折线
  map.addPolyline({
    path: path,
    strokeWidth: 6,
    strokeColor: '#4CAF50',
    strokeAlpha: 0.8,
    lineCap: 'round',
    lineJoin: 'round',
  });
}

4.2 显示海拔范围

function showElevationRange(map: MapView, points: Coordinate[]): void {
  const altitudes = points.map(p => p.altitude);
  const minAlt = Math.min(...altitudes);
  const maxAlt = Math.max(...altitudes);

  map.addInfoWindow({
    position: {
      lat: points[0].latitude,
      lng: points[0].longitude,
    },
    title: `海拔范围: ${minAlt}m - ${maxAlt}m`,
  });
}

五、当前位置定位

import { geoLocationManager } from '@kit.LocationKit';

async function getCurrentLocation(): Promise<{
  lat: number;
  lng: number;
}> {
  try {
    // 请求定位
    const location = await geoLocationManager.getCurrentLocation({
      priority: 0x201,           // 高精度定位
      timeoutMs: 10000,          // 超时
    });

    return {
      lat: location.latitude,
      lng: location.longitude,
    };
  } catch (err) {
    console.error('定位失败:', err);
    throw err;
  }
}

// 在地图上显示当前位置
async function showMyLocation(map: MapView): Promise<void> {
  try {
    const pos = await getCurrentLocation();

    // 移动地图中心到当前位置
    map.moveCamera({
      target: { lat: pos.lat, lng: pos.lng },
      zoom: 16,
      duration: 500,
    });

    // 添加当前位置标记
    map.addMarker({
      position: { lat: pos.lat, lng: pos.lng },
      title: '我的位置',
      icon: 'current_location_icon',
    });
  } catch (err) {
    console.error('显示位置失败:', err);
  }
}

六、实战:徒步迹首页地图

@Component
struct HomeMapView {
  private mapView!: MapView;

  build() {
    Column() {
      MapComponent({
        mapOptions: {
          center: { lat: 39.908, lng: 116.397 },
          zoom: 14,
          mapType: MapType.NORMAL,  // 普通地图
        },
        onMapReady: (map: MapView) => {
          this.mapView = map;
          this.initMap();
        },
      })
      .width('100%')
      .height(200)
      .borderRadius(16);
    }
    .padding(16);
  }

  initMap(): void {
    // 添加附近路线标记
    this.addNearbyRoutes();
  }

  addNearbyRoutes(): void {
    const routes = [
      { lat: 39.910, lng: 116.400, name: '香山环线' },
      { lat: 39.920, lng: 116.390, name: '植物园路线' },
    ];

    for (let route of routes) {
      this.mapView.addMarker({
        position: { lat: route.lat, lng: route.lng },
        title: route.name,
      });
    }
  }
}

七、总结

MapKit 组件让在鸿蒙 App 中集成地图变得简单。从基础地图显示、标记添加到路线绘制和定位,这些能力构成了徒步迹轨迹记录和路线展示的基础。

下一篇文章将继续优化地图体验,实现自定义标记和气泡弹窗。


下一篇预告:鸿蒙原生开发手记:徒步迹 - 自定义地图标记与气泡弹窗

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐