【鸿蒙开发】第四十四章 Map Kit(地图服务)

news2025/2/22 20:14:41

目录​​​​​​​

1 Map Kit简介

1.1 场景介绍

2 开发准备 

开通地图服务

3 创建地图

3.1 显示地图

3.1.1 接口说明

3.1.2 开发步骤

1、地图显示

2、设置地图属性

3、开启3D建筑图层

4、地图前后台切换

5、深色模式

3.2 切换地图类型

3.2.1 场景介绍

3.2.2 接口说明

3.2.3 开发步骤

 3.3 显示我的位置

3.3.1 接口说明

3.3.2 开发步骤

1、开启“我的位置”按钮

 2、监听“我的位置”按钮点击事件

3、隐藏“我的位置”按钮

4、自定义位置图标样式

3.4 显示自定义地图

3.4.1 接口说明

3.4.2 开发步骤

1、设置样式ID

 2、设置样式内容

3、样式参考

4 地图交互

4.1 控件交互

4.1.1 接口说明

4.1.2 开发步骤

1、缩放控件

2、比例尺

3、指南针

4、地图Logo

4.2 手势交互

4.2.1 接口说明

4.2.2 地图手势控制

1、缩放手势:

2、滚动平移手势:

3、旋转手势:

4、倾斜手势:

5、启用或禁止所有手势:

4.3 事件交互

4.3.1 接口说明

4.3.2 开发步骤

1、 初始化地图组件的事件管理接口

2、 地图点击事件监听

3、 地图长按事件监听

4、 相机移动监听

5、 标记点击事件监听

6、我的位置监听

7、点注释事件监听

4.4 更改地图位置

4.4.1 接口说明

4.4.2 开发步骤

1、相机移动

2、设置相机最大/最小偏好缩放级别

3、设置地图相机的边界

4.5 地图截图

4.5.1 接口说明

4.5.2 开发步骤

5. 地图绘制

5.1 标记

5.1.1 接口说明

5.1.2 开发步骤

1、添加标记

2、自定义标记 

3、设置监听标记点击事件

4、设置监听标记拖动事件

5、信息窗

6、自定义信息窗​​​​​​​

7、标记动画

8、图片动画播放

 5.2 折线

5.2.1 接口说明

5.2.2 开发步骤

1、添加折线

2、设置折线分段颜色

3、设置折线可渐变

4、绘制纹理

5.3 弧线

5.3.1 接口说明

5.3.2 开发步骤

1、添加弧线

 5.4 多边形

5.4.1 接口说明

5.4.2 开发步骤

5.5 圆形

5.5.1 接口说明

5.5.2 开发步骤

 5.6 点注释

5.6.1 接口说明

5.6.2 开发步骤

1、添加点注释

2、设置监听点注释点击事件

 3、点注释动画

4、点注释标题动画 

5.7 气泡

5.7.1 接口说明

5.7.2 开发步骤

1、添加气泡

2、设置监听气泡点击事件

3、气泡动画

5.8 点聚合

5.8.1 接口说明

5.8.2 开发步骤

5.9 覆盖物

5.9.1 接口说明

5.9.2 开发步骤

 5.10 3D建筑

5.10.1 接口说明

5.10.2 开发步骤

1、添加3D建筑

 5.11 动态轨迹

5.11.1 接口说明

5.11.2 开发步骤

5.12 设置地图元素压盖顺序

5.12.1 概述

5.12.2 接口说明

5.12.3 开发步骤

6 位置搜索

6.1 Poi搜索

6.1.1 场景介绍

6.1.2 接口说明

6.1.3 开发步骤

1、关键字搜索

2、周边搜索

3、自动补全

4、地点详情

6.2 地理编码

6.2.1 场景介绍

6.2.2 接口说明

6.2.3 开发步骤

1、正地理编码

2、逆地理编码

7 路径规划

7.1 出行路线规划

7.1.1 场景介绍

7.1.2 接口说明

7.1.3 开发步骤

1、驾车路径规划

2、步行路径规划

 3、骑行路径规划

7.2 批量算路

7.2.1 场景介绍

7.2.2 接口说明

7.2.3 开发步骤

1、驾车批量算路

2、步行批量算路

3、骑行批量算路

7.3 轨迹绑路

7.3.1 场景介绍

7.3.2 接口说明

7.3.3 开发步骤

1、轨迹绑路

8 静态图 

8.1 场景介绍

8.2 接口说明

8.3 开发步骤

9 地图Picker

9.1 地点详情展示

9.1.1 场景介绍

9.1.2 接口说明

9.1.3 开发步骤

9.2 地点选取

9.2.1 场景介绍

9.2.2 接口说明

9.2.3 开发步骤

9.3 区划选择

9.3.1 场景介绍

9.3.2 接口说明

9.3.3 开发步骤

10. 通过Petal 地图应用实现导航等能力

10.1 通过AppLinking拉起Petal Maps鸿蒙应用APP

10.2 拉起方实现跳转

10.3 Petal 地图使用的坐标类型

10.4 拉起Petal 地图首页

10.5 拉起Petal 地图查看位置详情

拉起Petal 地图查看路径规划

拉起Petal 地图发起导航

拉起Petal 地图进行位置搜索


1 Map Kit简介

Map Kit(地图服务)为开发者提供强大而便捷的地图能力,助力全球开发者实现个性化显示地图、位置搜索和路径规划等功能,轻松完成地图构建工作。您可以轻松地在HarmonyOS应用/元服务中集成地图相关的功能,全方位提升用户体验。

Map Kit提供了全球3.2亿的 Poi(Point of Interest,兴趣点)。在地图表达中,一个 Poi 可代表一家商铺、一栋办公楼、一处景点等等。

1.1 场景介绍

中国大陆使用GCJ02坐标系,中国台湾和海外使用WGS84坐标系。详见坐标转换。

Map Kit提供以下功能,满足绝大多数地图开发的需求:

  • 创建地图:呈现内容包括建筑、道路、水系等。
  • 地图交互:控制地图的交互手势和交互按钮。
  • 在地图上绘制:添加位置标记、覆盖物以及各种形状等。
  • 位置搜索:多种查询Poi信息的能力。
  • 路径规划:提供驾车、步行、骑行路径规划能力。
  • 静态图:获取一张地图图片。
  • 地图Picker:提供地点详情展示控件、地点选取控件、区划选择控件。
  • 通过Petal 地图应用实现导航等能力:查看位置详情、查看路径规划、发起导航、发起内容搜索。
  • 地图计算工具:华为地图涉及的2种坐标系及其使用区域和转换。

2 开发准备 

开通地图服务

  1. 登录AppGallery Connect网站,选择“我的项目”。

  2. 在项目列表中找到您的项目,在项目下的应用列表中选择需要打开“地图服务”的应用。

  3. 选择API管理,找到“地图服务”开关,打开开关。

  4. 确认已经开启“地图服务”开放能力,并完成手动签名。

说明

若使用原有的Profile文件,请确保在申请Profile文件之前已开启“地图服务”,否则开启后需要重新申请Profile文件,并重新配置签名信息。

3 创建地图

3.1 显示地图

通过地图组件MapComponent和MapComponentController呈现地图

3.1.1 接口说明

显示地图功能主要由MapComponent提供,更多接口及使用方法请参见接口文档。

接口

接口描述

mapCommon.MapOptions

提供Map组件初始化的属性。

MapComponent(mapOptions: mapCommon.MapOptions, mapCallback: AsyncCallback<map.MapComponentController>)

地图组件。

map.MapComponentController

地图组件的主要功能入口类,用来操作地图,与地图有关的所有方法从此处接入。它所承载的工作包括:地图类型切换(如标准地图、空地图)、改变地图状态(中心点坐标和缩放级别)、添加点标记(Marker)、绘制几何图形(如MapPolyline、MapPolygon、MapCircle)、监听各类事件等。

3.1.2 开发步骤

1、地图显示

        1. 导入Map Kit相关模块。

import { MapComponent, mapCommon, map } from '@kit.MapKit';
import { AsyncCallback } from '@kit.BasicServicesKit';

        2. 新建地图初始化参数mapOptions,设置地图中心点坐标及层级。

通过callback回调的方式获取MapComponentController对象,用来操作地图。

调用MapComponent组件,传入mapOptions和callback参数,初始化地图。

@Entry
@Component
struct HuaweiMapDemo {
  private TAG = "HuaweiMapDemo";
  private mapOptions?: mapCommon.MapOptions;
  private callback?: AsyncCallback<map.MapComponentController>;
  private mapController?: map.MapComponentController;
  private mapEventManager?: map.MapEventManager;

  aboutToAppear(): void {
    // 地图初始化参数,设置地图中心点坐标及层级
    this.mapOptions = {
      position: {
        target: {
          latitude: 39.9,
          longitude: 116.4
        },
        zoom: 10
      }
    };

    // 地图初始化的回调
    this.callback = async (err, mapController) => {
      if (!err) {
        // 获取地图的控制器类,用来操作地图
        this.mapController = mapController;
        this.mapEventManager = this.mapController.getEventManager();
        let callback = () => {
          console.info(this.TAG, `on-mapLoad`);
        }
        this.mapEventManager.on("mapLoad", callback);
      }
    };
  }

  // 页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效
  onPageShow(): void {
    // 将地图切换到前台
    if (this.mapController) {
      this.mapController.show();
    }
  }

  // 页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景,仅@Entry装饰的自定义组件生效
  onPageHide(): void {
    // 将地图切换到后台
    if (this.mapController) {
      this.mapController.hide();
    }
  }

  build() {
    Stack() {
      // 调用MapComponent组件初始化地图
      MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback }).width('100%').height('100%');
    }.height('100%')
  }
}

        3. 运行刚完成的工程就可以看到地图了,运行后的效果如下图所示。

2、设置地图属性

MapOptions包含以下属性。

属性

描述

mapType

地图类型,默认值:MapType.STANDARD。

position

地图相机位置。

bounds

地图展示框。

minZoom

地图最小图层,有效范围[2, 20],默认值:2。

maxZoom

地图最大图层,有效范围[2, 20],默认值:20。

rotateGesturesEnabled

是否支持旋转手势,默认值:true。

scrollGesturesEnabled

是否支持滑动手势,默认值:true。

zoomGesturesEnabled

是否支持缩放手势,默认值:true。

tiltGesturesEnabled

是否支持倾斜手势,默认值:true。

zoomControlsEnabled

是否展示缩放控件,默认值:true。

myLocationControlsEnabled

是否展示我的位置按钮,默认值:false。

compassControlsEnabled

是否展示指南针控件,默认值:true。

scaleControlsEnabled

是否展示比例尺,默认值:false。

alwaysShowScaleEnabled

是否始终显示比例尺,默认值:false。

padding

设置地图和边界的距离。

styleId

自定义样式ID。

dayNightMode

日间夜间模式,默认值:DayNightMode.DAY(日间模式)。

  1. 设置mapType,切换地图类型章节中有详细讲解。
  2. 设置myLocationControlsEnabled,展示我的位置按钮。

    在mapOptions中设置myLocationControlsEnabled属性为true,可展示我的位置按钮,显示效果如下图所示。

    也可通过调用MapComponentController对象的方法展示我的位置按钮,详情见显示我的位置章节。

this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 10
  },
  myLocationControlsEnabled: true
};

 

 3. 展示比例尺。

在mapOptions中设置scaleControlsEnabled属性为true,可展示比例尺,显示效果如下图所示。

this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 10
  },
  scaleControlsEnabled: true
};

3、开启3D建筑图层

调用MapComponentController对象的setBuildingEnabled方法开启3D建筑图层,将两个手指放在地图上,向上滑动倾斜地图可看到3D建筑图层的效果。

this.mapController.setBuildingEnabled(true);

显示效果如下:

4、地图前后台切换

通过MapComponentController对象来控制地图页面前后台切换的生命周期。应用触发前后台切换时,可以在Page生命周期里调用show/hide,以便申请/释放资源。

地图切换至前台:

// 页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效
onPageShow(): void {
  // 建议页面切换到前台,调用地图组件的show方法 
  if (this.mapController) {
    this.mapController.show();
  }
}

 地图切换至后台:

// 页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景,仅@Entry装饰的自定义组件生效
onPageHide(): void {
  // 建议页面切换到后台,调用地图组件的hide方法
  if (this.mapController) {
    this.mapController.hide();
  }
}
5、深色模式

Map Kit提供2种方式设置地图的夜间模式:初始化地图时和创建地图后。

方式一:初始化地图时

在地图初始化参数中设置dayNightMode参数,参数可选值包括DAY(日间模式)、NIGHT(夜间模式)、AUTO(自动模式)。如果将参数值设置为AUTO,地图的深色模式会跟随系统,打开系统深色开关,显示夜间模式,否则显示日间模式。

this.mapOptions = {
  position: {
    target: {
      latitude: 39.9,
      longitude: 116.4
    },
    zoom: 10
  },
  myLocationControlsEnabled: true,
  // 设置地图为夜间模式
  dayNightMode: mapCommon.DayNightMode.NIGHT
};

方式二:创建地图后

创建地图后,可调用MapComponentController对象的setDayNightMode方法设置夜间模式。下面的例子中将参数值设置为AUTO,在设置完之后,打开系统的深色开关,地图会自动变为夜间模式。

// 设置地图为自动模式
this.mapController.setDayNightMode(mapCommon.DayNightMode.AUTO);

3.2 切换地图类型

3.2.1 场景介绍

Map Kit支持以下地图类型:

  • STANDARD:标准地图,展示道路、建筑物以及河流等重要的自然特征。
  • NONE:空地图,没有加载任何数据的地图。
  • TERRAIN:地形图。

图1 标准地图

图2 空地图

图3 地形图

  

3.2.2 接口说明

Map Kit提供2种方式设置地图类型:

方式一:在初始化的时候,通过设置MapOptions中的MapType来控制展示不同地图类型。

属性名

描述

mapCommon.MapOptions.MapType

地图初始化参数中的MapType地图类型。

方式二:地图创建后,可通过setMapType方法动态设置地图类型。

方法名

描述

setMapType(mapType: mapCommon.MapType): void

设置地图类型。

3.2.3 开发步骤

1. 导入相关模块。

import { mapCommon } from '@kit.MapKit';

2. 设置地图类型。

方式一:

在地图初始化的时候,在mapOptions参数中新增mapType属性:mapCommon.MapType.STANDARD。

this.mapOptions = {
  position: {
    target: {
      latitude: 31.984410259206815,
      longitude: 118.76625379397866
    },
    zoom: 15
  },
  mapType: mapCommon.MapType.STANDARD
};

    显示效果如下:

    方式二:地图创建后,调用setMapType方法设置地图类型为地形图。

    this.mapController.setMapType(mapCommon.MapType.TERRAIN);

    显示效果如下:

     3.3 显示我的位置

    3.3.1 接口说明

    “我的位置”功能主要由MapComponentController的方法实现,更多接口及使用方法请参见接口文档。

    方法名

    描述

    setMyLocationEnabled(myLocationEnabled: boolean): void

    “我的位置”图层功能开关,默认使用系统的连续定位能力显示用户位置。开关打开后,“我的位置”按钮默认显示在地图的右下角。点击“我的位置”按钮,将会在屏幕中心显示当前定位,以蓝色圆点的形式呈现。

    setMyLocationControlsEnabled(enabled: boolean): void

    设置是否启用“我的位置”按钮。只显示按钮,在不开启“我的位置”图层功能的情况下,点击按钮没反应。

    setMyLocation(location: geoLocationManager.Location): void

    设置“我的位置”坐标。

    如果不使用Map Kit提供的默认定位行为,可以通过Location Kit获取用户位置后,传给Map Kit。

    setMyLocationStyle(style: mapCommon.MyLocationStyle): Promise<void>

    设置“我的位置”样式。

    on(type: 'myLocationButtonClick', callback: Callback<void>): void

    监听“我的位置”按钮点击事件。

    off(type: 'myLocationButtonClick', callback?: Callback<void>): void

    取消监听“我的位置”按钮点击事件。

    3.3.2 开发步骤

    1、开启“我的位置”按钮
    1. 启用“我的位置”之前,需要确保应用可以获取用户定位。获取用户定位有两种方式:

      方式一(推荐):使用安全控件LocationButton。

      方式二:申请ohos.permission.LOCATION和ohos.permission.APPROXIMATELY_LOCATION权限,需要在module.json5配置文件中声明所需要的权限,具体可参考声明权限。

    {
      "module" : {
        // ...
        "requestPermissions":[
          {
            // 允许应用在前台运行时获取位置信息
            "name" : "ohos.permission.LOCATION",
            // reason需要在/resources/base/element/string.json中新建
            "reason": "$string:location_permission",
            "usedScene": {
              "abilities": [
                "EntryAbility"
              ],
              "when":"inuse"
            }
          },
          {
            // 允许应用获取设备模糊位置信息
            "name" : "ohos.permission.APPROXIMATELY_LOCATION",
            // reason需要在/resources/base/element/string.json中新建
            "reason": "$string:approximately_location_permission",
            "usedScene": {
              "abilities": [
                "EntryAbility"
              ],
              "when":"inuse"
            }
          }
        ]
      }
    }

    2. 初始化地图并获取MapComponentController地图操作类对象。显示地图章节中有详细讲解。

    3. 调用mapController对象的setMyLocationEnabled方法启用“我的位置”功能。

    1)如果是通过方式一申请用户定位权限,可以在点击安全控件后打开地图,并开启“我的位置”功能。

    // 启用我的位置图层
    this.mapController.setMyLocationEnabled(true);
    // 启用我的位置按钮
    this.mapController.setMyLocationControlsEnabled(true);

     2)如果是通过方式二申请用户定位权限,建议在获得用户授权后开启“我的位置”功能。

    import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    // 校验应用是否被授予定位权限,可以通过调用checkAccessToken()方法来校验当前是否已经授权。
    async checkPermissions(): Promise<boolean> {
      const permissions: Array<Permissions> = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];
      for (let permission of permissions) {
        let grantStatus: abilityAccessCtrl.GrantStatus = await this.checkAccessToken(permission);
        if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
          // 启用我的位置图层,mapController为地图操作类对象,获取方式详见显示地图章节
          this.mapController?.setMyLocationEnabled(true);
          // 启用我的位置按钮
          this.mapController?.setMyLocationControlsEnabled(true);
          return true;
        }
      }
      return false;
    }
    
    // 如果没有被授予定位权限,动态向用户申请授权
    requestPermissions(): void {
      let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
      atManager.requestPermissionsFromUser(getContext() as common.UIAbilityContext, ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
        .then((data: PermissionRequestResult) => {
          // 启用我的位置图层
          this.mapController?.setMyLocationEnabled(true);
        })
        .catch((err: BusinessError) => {
          console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
        })
    }
    
    async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
      let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
      let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;
    
      // 获取应用程序的accessTokenID
      let tokenId: number = 0;
      let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
      console.info('Succeeded in getting Bundle.');
      let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
      tokenId = appInfo.accessTokenId;
    
      // 校验应用是否被授予权限
      grantStatus = await atManager.checkAccessToken(tokenId, permission);
      console.info('Succeeded in checking access token.');
      return grantStatus;
    }

     4. 检查“我的位置”功能是否成功启用。

    “我的位置”按钮默认显示在地图的右下角。点击“我的位置”按钮,将会在屏幕中心显示当前定位,以蓝色圆点的形式呈现,效果如下图所示,效果根据获取到的用户位置会有变化。

    5. 获取用户位置坐标并设置用户的位置。

    Map Kit默认使用系统的连续定位能力,如果您希望定制显示频率或者精准度,可以调用geoLocationManager相关接口获取用户位置坐标(WGS84坐标系)。注意访问设备的位置信息必须申请权限,并且获得用户授权,详情见geoLocationManager。

    下面的示例仅显示一次定位结果,在获取到用户坐标后,调用mapController对象的setMyLocation(location: geoLocationManager.Location)设置用户的位置。setMyLocation接口使用的是WGS84坐标系,如果用户位置在大陆、香港、澳门,需将WGS84坐标转换成GCJ02坐标系,详见坐标转换。

    // 需要引入@kit.LocationKit模块
    import { geoLocationManager } from '@kit.LocationKit';
    // ...
    
    // 获取用户位置坐标
    let location = await geoLocationManager.getCurrentLocation();
    
    // 设置用户的位置
    this.mapController.setMyLocation(location);
     2、监听“我的位置”按钮点击事件

    通过调用on(type: 'myLocationButtonClick')方法,设置'myLocationButtonClick'事件监听。设置监听后“我的位置按钮”点击事件自定义,反之不设置则由Map Kit执行点击后默认事件,即地图移动到当前用户位置。

    let callback = () => {
      console.info("myLocationButtonClick", `myLocationButtonClick`);
    };
    this.mapEventManager.on("myLocationButtonClick", callback);
    3、隐藏“我的位置”按钮

    控制是否显示“我的位置”按钮。

    this.mapController.setMyLocationControlsEnabled(false);
    4、自定义位置图标样式

    通过调用mapController.setMyLocationStyle(style: mapCommon.MyLocationStyle)方法,设置用户位置图标样式。效果如下:

    let style: mapCommon.MyLocationStyle = {
      anchorU: 0.5,
      anchorV: 0.5,
      radiusFillColor: 0xffff0000,
      // icon为自定义图标资源,使用时需要替换
      // 图标存放在resources/rawfile,icon参数传入rawfile文件夹下的相对路径
      icon: 'test.png'
    };
    await this.mapController.setMyLocationStyle(style);

    3.4 显示自定义地图

    3.4.1 接口说明

    自定义样式功能主要由CustomMapStyleOptions、setCustomMapStyle提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    CustomMapStyleOptions

    自定义样式参数。

    setCustomMapStyle(customMapStyleOptions: mapCommon.CustomMapStyleOptions): Promise<void>

    将地图样式修改为自定义样式。

    3.4.2 开发步骤

    Map Kit提供两种方法设置自定义地图样式:

    • 设置样式ID:使用Petal Maps Studio管理地图样式,并使用样式ID将它们链接到您的地图上。您可以在Petal Maps Studio上创建新样式,或导入现有样式定义。样式一旦发布,使用此样式的应用都会自动应用新样式。
    • 设置样式内容:通过传入自定义JSON更改地图样式,JSON的定义参见样式参考。
    1、设置样式ID

    1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

    2. 创建样式ID。

    • 登录Petal Maps Studio。

    • 点击“Create map”创建自定义样式。

    •  导入JSON样式文件,点击“Import”。

    • 在编辑器里修改样式。

    • 点击“SAVE”生成预览ID,预览ID在编辑样式时会重新生成,您可以通过预览ID测试样式效果。点击“PUBLISH”发布生成样式ID,样式ID是唯一ID,一旦发布生效不会变化。 

    3. Map Kit提供两种方法设置样式ID:

    • 在创建地图后设置样式ID
    @Entry
    @Component
    struct CustomMapStyleDemo {
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        // 地图初始化参数
        this.mapOptions = {
          position: {
            target: {
              latitude: 31.984410259206815,
              longitude: 118.76625379397866
            },
            zoom: 15
          }
        };
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
            // 自定义样式参数,styleId需要替换为您自己的样式ID或者预览ID,样式ID或者预览ID可在Petal Maps Studio平台上创建
            let param: mapCommon.CustomMapStyleOptions = {
               styleId: "1346407266336828736"
            };
            // 设置自定义样式
            await this.mapController.setCustomMapStyle(param);
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
          }.width('100%')
        }.height('100%')
      }
    }
    •  在初始化地图时设置样式ID
    @Entry
    @Component
    struct CustomMapStyleDemo {
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        // 地图初始化参数
        this.mapOptions = {
          position: {
            target: {
              latitude: 31.984410259206815,
              longitude: 118.76625379397866
            },
            zoom: 15
          },
          // 自定义样式参数,styleId需要替换为您自己的样式ID或者预览ID,样式ID或者预览ID可在Petal Maps Studio平台上创建
          styleId: "1346407266336828736"
        };
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
          }.width('100%')
        }.height('100%')
      }
    }

     设置样式ID之后效果如下:

     2、设置样式内容

    1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

     2. 设置样式内容。

    @Entry
    @Component
    struct CustomMapStyleDemo {
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        // 地图初始化参数
        this.mapOptions = {
          position: {
            target: {
              latitude: 31.984410259206815,
              longitude: 118.76625379397866
            },
            zoom: 15
          }
        };
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
            // 自定义样式参数
            let param: mapCommon.CustomMapStyleOptions = {
                   styleContent: `[{
                       "mapFeature": "landcover.natural",
                       "options": "geometry.fill",
                       "paint": {
                           "color": "#8FBC8F"
                       }},
                       {
                      "mapFeature": "water",
                      "options": "geometry.fill",
                      "paint": {
                          "color": "#4682B4"
                      }}]`
            };
            // 设置自定义样式
            await this.mapController.setCustomMapStyle(param);
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
          }.width('100%')
        }.height('100%')
      }
    }

    3、样式参考

    自定义地图样式JSON内容通过下列4个元素来定义地图样式:

    • mapFeature:地图要素
    • options:元素选项
      • geometry.fill:几何填充
      • geometry.stroke:几何描边
      • geometry.icon:几何图标
      • labels.text.fill:文本填充
      • labels.text.stroke:文本描边
    • paint:绘制属性
      • color:颜色,16进制颜色,例如“#FFFF00”
      • weight:线条宽度。整型值,[0, 8],默认为0,大于0表示加宽
      • saturation:饱和度。整型值,[-100, 100],默认为0
      • lightness:亮度。整型值,[-100, 100],默认为0
      • icon-type:图标类型,目前支持night、simple、standard
    • visibility:可见属性,默认为复用模板
      • inherit:复用模板
      • hidden:隐藏
      • shown:显示

    下列各表将展示支持修改的地图元素。

    说明

    • 图标类型icon-type支持范围为:standard/night/simple。
    • 饱和度Saturation和亮度Lightness可在元素颜色Color中进行配置。
    1. All

      All代表全部,即所有类别的集合,支持能力范围同其他所有列表。

    2. Administrative

      元素类型

      Feature type

      Geometry

      Labels

      Icon

      填充颜色

      fill.

      color

      填充宽度

      fill.

      weight

      描边颜色

      stroke.

      color

      描边宽度

      stroke.

      weight

      填充颜色

      fill.

      color

      文本大小

      fill.

      weight

      描边颜色

      stroke.

      color

      描边大小

      stroke.

      weight

      图标类型

      icon-

      type

      capital

      首都

      -

      -

      -

      -

      Country

      国家

      -

      District

      区/县

      -

      -

      -

      -

      Locality

      乡村、城镇

      -

      -

      -

      -

      Major-city

      1-4级城市

      -

      -

      -

      -

      Province

      -

    3. Landcover

      元素类型

      Feature type

      Geometry

      Labels

      填充颜色

      fill.color

      描边颜色

      stroke.color

      填充颜色

      fill.color

      文本大小

      fill.weight

      描边颜色

      stroke.color

      描边大小

      stroke.weight

      Attraction

      游乐场、动植物园等

      -

      Business

      购物中心、商业区等

      -

      College

      学校

      -

      Hospital

      医院

      -

      Human-made

      聚集区、小区、工业区、监狱地面等

      Human-made

      建筑物

      -

      -

      -

      -

      Natural

      陆地、岛屿、海滩、冰川等

      -

      Parkland

      森林、公园、荒地、高尔夫球场等

      -

    4. Poi

      元素类型

      Feature type

      Labels

      Icon

      填充颜色

      fill.color

      文本大小

      fill.weight

      描边颜色

      stroke.color

      描边大小

      stroke.weight

      图标类型

      icon-type

      Airport

      飞机场

      Automotive

      汽修、充电桩、洗车等

      Beauty

      美容中心

      Business

      公司、商业楼等

      Eating&drinking

      饮食快餐

      Health-care

      医院、诊所、药店等

      Leisure

      休闲娱乐

      Lodging

      酒店、住宿点

      Miscellaneous

      自然地物

      Natural

      山峰、森林等

      Public-service

      医院、诊所、药店等

      Railway

      铁路

      Shopping

      购物中心、市场等

      Sports

      outdoor户外运动、爬山、骑车等

      Tourism

      旅游景点、历史遗迹、教堂等

    5. Road

      元素类型

      Feature type

      Geometry

      Labels

      Icon

      填充颜色

      fill.

      color

      填充宽度

      fill.

      weight

      描边颜色

      stroke.

      color

      描边宽度

      stroke.

      weight

      填充颜色

      fill.

      color

      文本大小

      fill.

      weight

      描边颜色

      stroke.

      color

      描边大小

      stroke.

      weight

      图标类型

      icon-

      type

      City-arterial

      城市主干道

      Highway

      城市高速

      Minor-road

      市区内支线等

      -

      National

      国道

      Province

      省道

      Sidewalk

      人行道

      -

    6. Trafficinfo

      元素类型

      Feature type

      Geometry

      Labels

      填充颜色

      fill.color

      填充颜色

      fill.color

      文本大小

      fill.weight

      Closed

      封路

    7. Transit

      元素类型

      Feature type

      Geometry

      Labels

      Icon

      填充颜色

      fill.

      color

      填充宽度

      fill.

      weight

      描边颜色

      stroke.

      color

      描边宽度

      stroke.weight

      填充颜色

      fill.

      color

      文本大小

      fill.

      weight

      描边颜色

      stroke.

      color

      描边大小

      stroke.weight

      图标类型

      icon-

      type

      Airport

      机场

      -

      -

      -

      Airport Runway

      机场跑道

                

      Airport Runway Taxiway

      机场跑道滑行道

                

      Bus

      公交

      -

      -

      -

      -

      Ferry-line

      航线

      -

      -

      -

      -

      Ferry-terminal

      港口

      -

      -

      -

      Other

      出租车、

      出入口等

      -

      -

      -

      -

      Rail-station

      火车站、

      高铁站

      -

      -

      -

      Railway

      铁路线、

      高铁线

      -

      -

      -

      -

      -

      Subway

      地铁

      Traffic_light

      交通灯

                      

    8. Water

      元素类型

      Feature type

      Geometry

      Labels

      填充颜色

      fill.color

      填充颜色

      fill.color

      文本大小

      fill.weight

      Ocean

      水系、海洋、湖泊、河流

    4 地图交互

    4.1 控件交互

    控件是指浮在地图组件上的一系列用于操作地图的组件,例如缩放按钮 、定位按钮、比例尺等。

    4.1.1 接口说明

    以下是地图的控件相关接口,该功能有2种实现方式:

    • 地图初始化时,可在初始化参数MapOptions中设置是否启用控件功能,详细讲解见显示地图章节。
    • 通过调用MapComponentController提供的set方法实现相关控件的开启或关闭。

    接口名

    描述

    setZoomControlsEnabled(enabled: boolean): void

    设置是否启用缩放控制器。

    setMyLocationEnabled(myLocationEnabled: boolean): void

    设置是否启用我的位置图层。

    setMyLocationControlsEnabled(enabled: boolean): void

    设置是否启用我的位置按钮。

    setScaleControlsEnabled(enabled: boolean): void

    设置是否启用比例尺。

    setScalePosition(point: mapCommon.MapPoint): void

    设置比例尺控件的位置。

    setAlwaysShowScaleEnabled(enabled: boolean): void

    设置是否始终显示比例尺。

    setCompassControlsEnabled(enabled: boolean): void

    设置是否启用指南针。

    4.1.2 开发步骤

    mapController对象在初始化地图时获取,初始化地图功能在显示地图章节中有详细讲解。

    1、缩放控件

    Map Kit提供了内置的缩放控件,默认情况下是开启的。

    this.mapController.setZoomControlsEnabled(true);

    2、比例尺

    Map Kit提供了内置的比例尺控件,默认情况下是关闭的。

    // 开启比例尺控件  
    this.mapController.setScaleControlsEnabled(true);

    调整比例尺位置:

    可通过setScalePosition方法设置比例尺控件的位置。

    let point: mapCommon.MapPoint = {
      // 以当前地图组件左上角为原点,向右移动1000px
      positionX: 1000,
      // 以当前地图组件左上角为原点,向下移动1000px
      positionY: 1000
    };
    this.mapController.setScalePosition(point);

     

    获取当前层级的比例尺大小:

    可通过getScaleLevel方法获取当前层级比例尺大小。

    let level = this.mapController.getScaleLevel();

    获取比例尺控件宽高:

    可通过getScaleControlsHeight和getScaleControlsWidth方法获取当前比例尺控件宽高。

    // 获取比例尺控件的高度
    let height = this.mapController.getScaleControlsHeight();
    // 获取比例尺控件的宽度
    let width = this.mapController.getScaleControlsWidth();

    设置比例尺控件常显:

    可通过setAlwaysShowScaleEnabled方法设置比例尺控件常显,通过isAlwaysShowScaleEnabled方法查询比例尺控件是否常显。

    // 设置比例尺控件常显
    this.mapController.setAlwaysShowScaleEnabled(true);
    // 查询比例尺控件是否常显
    let scaleEnabled: boolean = this.mapController.isAlwaysShowScaleEnabled();
    3、指南针

    Map Kit提供了内置的指南针控件,默认情况下是开启的,控件位置默认显示在地图的右上角。如果是启用状态,当地图不是指向正北方向或者发生倾斜时,地图右上角会显示一个指南针图标,点击指南针可使地图旋转为正北方向并且取消倾斜;当地图为正北方向且未发生倾斜时,指南针图标隐藏。如果是禁用状态,将不会显示指南针图标。

    // 开启指南针控件
    this.mapController.setCompassControlsEnabled(true);

    调整指南针位置:

    可通过setCompassPosition方法设置指南针控件的位置。

    let point: mapCommon.MapPoint = {
      // 以当前地图组件左上角为原点,向右移动1000px
      positionX: 1000,
      // 以当前地图组件左上角为原点,向下移动1000px
      positionY: 1000
    };
    this.mapController.setCompassPosition(point);

     

    4、地图Logo

    Map Kit提供了调整地图Logo对齐方式的方法setLogoAlignment和调整地图边界与Logo之间的间距的方法setLogoPadding。需注意,地图Logo不允许被遮挡,可通过setLogoPadding方法设置地图边界区域,来避免logo被遮挡。

    // 将Logo放置在右下角位置
    this.mapController.setLogoAlignment(mapCommon.LogoAlignment.BOTTOM_END);
    // 设置地图边界与Logo之间的间距,单位:px
    let padding: mapCommon.Padding = {
      right: 50,
      bottom: 50
    };
    this.mapController.setLogoPadding(padding);

     

    4.2 手势交互

    Map Kit提供了多种手势供用户与地图之间进行交互,如缩放、滚动、旋转和倾斜。这些手势默认开启,如果想要关闭某些手势,可以通过MapComponentController类提供的接口来控制手势的开关。

    4.2.1 接口说明

    以下是地图的手势相关接口,该功能有2种实现方式:

    • 地图初始化时,可在初始化参数mapOptions中设置是否启用手势功能,详细讲解见显示地图章节。
    • 通过调用MapComponentController提供的set方法实现相关手势的开启或关闭。

    接口名

    描述

    setZoomGesturesEnabled(enabled: boolean): void

    设置是否启用缩放手势。

    默认值为true。

    setScrollGesturesEnabled(enabled: boolean): void

    设置是否启用滚动手势。

    默认值为true。

    setRotateGesturesEnabled(enabled: boolean): void

    设置是否启用旋转手势。

    默认值为true。

    setTiltGesturesEnabled(enabled: boolean): void

    设置是否启用倾斜手势。

    默认值为true。

    setAllGesturesEnabled(enabled: boolean): void

    设置手势是否可用。

    默认值为true。

    4.2.2 地图手势控制

    mapController对象在初始化地图时获取,初始化地图功能在显示地图章节中有详细讲解。

    通过mapController对象来启用或禁止相关的地图手势。

    1、缩放手势:

    用户可以通过用双指张合,实现放大缩小地图。

    this.mapController.setZoomGesturesEnabled(true);
    2、滚动平移手势:

    用户可以通过用手指拖动地图来进行移动。

    this.mapController.setScrollGesturesEnabled(true);
    3、旋转手势:

    用户可以通过将两个手指放在地图上旋转来旋转地图。

    this.mapController.setRotateGesturesEnabled(true);
    4、倾斜手势:

    用户可以通过将两个手指放在地图上下滑动来倾斜地图。

    this.mapController.setTiltGesturesEnabled(true);
    5、启用或禁止所有手势:

    通过调用setAllGesturesEnabled方法,可启用或禁止所有手势。

    // 禁止所有手势
    this.mapController.setAllGesturesEnabled(false);

    4.3 事件交互

    包含地图的点击和长按、相机移动(华为地图的移动是通过模拟相机移动的方式实现的)、以及“我的位置”按钮点击等事件监听。

    4.3.1 接口说明

    以下是地图监听事件相关接口,以下功能主要由MapEventManager提供,可通过getEventManager方法获得MapEventManager。更多接口及使用方法请参见接口文档。

    接口名

    描述

    on(type: 'mapClick', callback: Callback<mapCommon.LatLng>): void

    设置地图点击事件监听器。

    on(type: 'mapLongClick', callback: Callback<mapCommon.LatLng>): void

    设置地图长按事件监听器。

    on(type: 'cameraMoveStart', callback: Callback<number>): void

    设置相机开始移动事件监听器。

    on(type: 'cameraMove', callback: Callback<void>): void

    设置相机移动事件监听器。

    on(type: 'cameraIdle', callback: Callback<void>): void

    设置相机移动结束事件监听器。

    on(type: 'markerClick' , callback: Callback<Marker>): void

    设置标记点击事件监听器。

    on(type: 'myLocationButtonClick', callback: Callback<void>): void

    设置我的位置按钮点击事件监听器。

    on(type: 'pointAnnotationClick', callback: Callback<PointAnnotation>): void

    设置点注释点击事件监听器。

    4.3.2 开发步骤

    1、 初始化地图组件的事件管理接口
    this.mapEventManager = this.mapController.getEventManager();
    2、 地图点击事件监听
    let callback = (position: mapCommon.LatLng) => {
      console.info("mapClick", `on-mapClick position = ${position.longitude}`);
    };
    this.mapEventManager.on("mapClick", callback);
    3、 地图长按事件监听
    let callback = (position: mapCommon.LatLng) => {
      console.info("mapLongClick", `on-mapLongClick position = ${position.longitude}`);
    };
    this.mapEventManager.on("mapLongClick", callback);
    4、 相机移动监听

    相机移动时(华为地图的移动是通过模拟相机移动的方式实现的),通过设置监听器,能够对相机移动状态进行监听。

    • 当相机开始移动时,会回调cameraMoveStart。
    let callback = (reason: number) => {
      console.info("cameraMoveStart", `on-cameraMoveStart reason = ${reason}`);
    };
    this.mapEventManager.on("cameraMoveStart", callback);
    • 当相机移动或用户与触摸屏交互时,会多次调用cameraMove。
    let callback = () => {
      console.info("cameraMove", `on-cameraMove`);
    };
    this.mapEventManager.on("cameraMove", callback);
    • 当相机停止移动时,会回调cameraIdle。
    let callback = () => {
      console.info("cameraIdle", `on-cameraIdle`);
    };
    this.mapEventManager.on("cameraIdle", callback);
    5、 标记点击事件监听

    标记是指在地图的指定位置添加标记以标识位置、商家、建筑等。

    let callback = (marker: map.Marker) => {
      console.info("markerClick", `markerClick: ${marker.getId()}`);
    };
    this.mapEventManager.on("markerClick", callback);
    6、我的位置监听
    let callback = () => {
      console.info("myLocationButtonClick", `myLocationButtonClick`);
    };
    this.mapEventManager.on("myLocationButtonClick", callback);
    7、点注释事件监听

    点注释是指在地图的指定位置添加点注释以标识位置、商家、建筑等,并可以通过信息窗口展示详细信息。

    let callback = (pointAnnotation: map.PointAnnotation) => {
      console.info("pointAnnotationClick", `pointAnnotationClick: ${pointAnnotation.getId()}`);
    };
    this.mapEventManager.on("pointAnnotationClick", callback);

    4.4 更改地图位置

    4.4.1 接口说明

    通过map命名空间下的moveCamera(update: CameraUpdate)方法、animateCamera(update: CameraUpdate, duration?: number)方法和animateCameraStatus(update: CameraUpdate, duration?: number)实现移动地图相机。方法入参CameraUpdate可通过以下方法创建。

    接口名

    描述

    zoomTo(zoom: number): CameraUpdate

    设置地图缩放级别。

    zoomOut(): CameraUpdate

    缩小地图缩放级别,在当前地图显示的级别基础上减1。

    zoomIn(): CameraUpdate

    放大地图缩放级别,在当前地图显示的级别基础上加1。

    zoomBy(amount: number, focus?: mapCommon.MapPoint): CameraUpdate

    根据给定增量并以给定的屏幕像素点为中心点缩放地图级别。

    scrollBy(x: number, y: number): CameraUpdate

    按像素移动地图中心点。

    newLatLngBounds(bounds: mapCommon.LatLngBounds, padding?: number): CameraUpdate

    设置地图经纬度范围;设置地图区域和边界之间的距离。

    newLatLngBounds(bounds: mapCommon.LatLngBounds, width: number, height: number, padding: number): CameraUpdate

    设置地图经纬度范围;设置经纬度矩形范围的高和宽;设置地图区域和边界之间的距离。

    newLatLng(latLng: mapCommon.LatLng, zoom?: number): CameraUpdate

    设置地图的中心点和缩放层级。

    newCameraPosition(cameraPosition: mapCommon.CameraPosition): CameraUpdate

    更新地图状态。

    4.4.2 开发步骤

    1、相机移动

        1. 初始化地图并获取MapComponentController地图操作类对象。显示地图章节中有详细讲解。

        2. 导入模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';

         3. 通过调用MapComponentController的moveCamera方法、animateCamera方法和animateCameraStatus方法,可实现移动地图相机。

    选择以动画方式或非动画方式移动相机。

    • 动画方式移动相机时,您可以设置动画持续的时间。
    • 非动画方式移动相机是瞬时完成的。
    // 创建CameraUpdate对象
    let cameraPosition: mapCommon.CameraPosition = {
      target: {
        latitude: 32.0,
        longitude: 118.0
      },
      zoom: 10,
      tilt: 0,
      bearing: 0
    };
    let cameraUpdate = map.newCameraPosition(cameraPosition);
    // 以非动画方式移动地图相机
    this.mapController.moveCamera(cameraUpdate);
    
    // 以动画方式移动地图相机
    this.mapController.animateCamera(cameraUpdate, 1000);
    
    // 以动画方式移动地图相机,并返回动画结果
    let animateResult = await this.mapController.animateCameraStatus(cameraUpdate, 1000);

    图3 相机移动前

    图4 相机移动后

          4. 还可以通过以下方式创建CameraUpdate对象。

    // 方式1:相机放大级数加1,保持其他属性不变
    let cameraUpdate = map.zoomIn();
    
    // 方式2:相机放大级数减1,保持其他属性不变
    let cameraUpdate1 = map.zoomOut();
    
    // 方式3:指定相机缩放级数zoom值,其他属性不变
    let zoom1 = 8.0;
    let cameraUpdate2 = map.zoomTo(zoom1);
    
    // 方式4:
    // a、指定相机缩放级别增量amount,您调用此方法可以在原来相机的缩放级别之上,进行适当的缩放
    // b、指定缩放级别增量和一个中心点,您调用此API可以移动相机至中心点位置,并进行缩放
    // 以屏幕左顶点为(0, 0)点,positionX正值代表可视区域向右移动,负值代表可视区域向左移动
    // positionY正值代表可视区域向下移动,负值代表可视区域向上移动
    let point: mapCommon.MapPoint = {
      positionX: 31,
      positionY: 118
    };
    let amount = 2.0;
    let cameraUpdate3 = map.zoomBy(amount, point);
    
    // 方式5:设置相机的经纬度和地图层级
    // a、仅指定相机的经纬度,实现中心点的移动
    // b、指定相机的经纬度和地图层级,您调用此API可以移动相机至中心点位置,并进行缩放
    let latLng: mapCommon.LatLng = {
      latitude: 31.5,
      longitude: 118.9
    };
    let zoom2 = 10;
    let cameraUpdate4 = map.newLatLng(latLng, zoom2);
    
    // 方式6:设置相机的可见区域
    let latLngBounds: mapCommon.LatLngBounds = {
      northeast: {
        latitude: 32.5,
        longitude: 119.9
      },
      southwest: {
        latitude: 31.5,
        longitude: 118.9
      }
    };
    // 设置地图显示经纬度范围,设置地图区域和边界之间的距离为5像素
    let cameraUpdate5 = map.newLatLngBounds(latLngBounds, 5);
    // 方式7:设置相机的可见区域
    // 设置地图显示经纬度范围,设置经纬度矩形范围的宽为9像素,设置经纬度矩形范围的高为16像素,设置地图区域和边界之间的距离为5像素
    let cameraUpdate6 = map.newLatLngBounds(latLngBounds, 9, 16, 5);
    // 方式8:滚动相机,将相机按照指定的像素点移动
    let x = 100.0;
    let y = 100.0;
    let cameraUpdate7 = map.scrollBy(x, y);
    2、设置相机最大/最小偏好缩放级别
    // 设置最小偏好缩放级别,范围为[2,20] 
    this.mapController.setMinZoom(6); 
    // 设置最大偏好缩放级别,范围为[2,20] 
    this.mapController.setMaxZoom(14);
    3、设置地图相机的边界

    Map Kit支持设置地图相机的边界。通过setLatLngBounds(bounds: mapCommon.LatLngBounds)接口指定一个LatLngBounds来约束相机目标,使用户移动地图时,相机目标不会移出此边界。当设置参数为空时,地图相机的边界清除。

    let bounds: mapCommon.LatLngBounds = {
      northeast: {
        latitude: 31,
        longitude: 118
      },
      southwest: {
        latitude: 30,
        longitude: 113
      }
    };
    this.mapController.setLatLngBounds(bounds);

    4.5 地图截图

    地图截图指对当前屏幕显示区域进行截屏,支持对地图、覆盖物、Logo进行屏幕截图。

    4.5.1 接口说明

    以下是地图截图相关接口,以下功能主要由snapshot提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    snapshot(): Promise<image.PixelMap>

    地图截图。

    4.5.2 开发步骤

            1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';
    import { image } from '@kit.ImageKit';

            2. 调用snapshot方法对当前屏幕进行截图。

    @Entry
    @Component
    struct HuaweiMapDemo {
      private mapOptions?: mapCommon.MapOptions;
      private callback?: AsyncCallback<map.MapComponentController>;
      private mapController?: map.MapComponentController;
      @State image?: image.PixelMap = undefined;
    
      aboutToAppear(): void {
        // 地图初始化参数,设置地图中心点坐标及层级
        this.mapOptions = {
          position: {
            target: {
              latitude: 39.9,
              longitude: 116.4
            },
            zoom: 10
          }
        };
    
        // 地图初始化的回调
        this.callback = async (err, mapController) => {
          if (!err) {
            // 获取地图的控制器类,用来操作地图
            this.mapController = mapController;
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback })
              .width('100%')
              .height('50%');
    
            Scroll(new Scroller()) {
              Column() {
                Image(this.image)
                  .objectFit(ImageFit.Auto)
                  .border({ width: 1, color: Color.Red }).width("100%")
                Button("获取截图")
                  .margin({ left: 10 })
                  .fontSize(12)
                  .onClick(async () => {
                    if (this.mapController) {
                      let pixelMap = await this.mapController.snapshot();
                      this.image = pixelMap;
                    }
                  });
              }
            }.width('70%').height("50%")
          }.width('100%')
        }.height('100%')
      }
    }

    5. 地图绘制

    5.1 标记

    5.1.1 接口说明

    添加标记功能主要由MarkerOptions、addMarker和Marker提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    MarkerOptions

    标记参数。

    addMarker(options: mapCommon.MarkerOptions): Promise<Marker>

    在地图上添加标记。

    Marker

    标记,支持更新和查询相关属性。

    5.1.2 开发步骤

    1、添加标记

            1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

            2. 添加标记,在Callback方法中创建初始化参数并新建Marker。

    @Entry
    @Component
    struct MarkerDemo {
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
      private mapEventManager?: map.MapEventManager;
      private marker?: map.Marker;
    
      aboutToAppear(): void {
        // 地图初始化参数
        this.mapOptions = {
          position: {
            target: {
              latitude: 31.984410259206815,
              longitude: 118.76625379397866
            },
            zoom: 15
          }
        };
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
            this.mapEventManager = this.mapController.getEventManager();
            // Marker初始化参数
            let markerOptions: mapCommon.MarkerOptions = {
              position: {
                latitude: 31.984410259206815,
                longitude: 118.76625379397866
              },
              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);
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
          }.width('100%')
        }.height('100%')
      }
    }

            3. 在添加标记之后,修改已经设置的标记属性。 

    // 设置标记可拖拽
    this.marker.setDraggable(true);
    // 设置标记锚点
    this.marker.setMarkerAnchor(1.0, 1.0);
    2、自定义标记 

    通过在MarkerOptions中将icon属性设置为自定义图标的资源,可将默认标记图标修改成自定义图标。

    let markerOptions: mapCommon.MarkerOptions = {
      position: {
        latitude: 31.984410259206815,
        longitude: 118.76625379397866
      },
      rotation: 0,
      visible: true,
      zIndex: 0,
      alpha: 1,
      anchorU: 0.5,
      anchorV: 1,
      clickable: true,
      draggable: true,
      flat: false,
      // 图标存放在resources/rawfile,icon参数传入rawfile文件夹下的相对路径
      icon: 'test.png'
    };
    this.marker = await this.mapController.addMarker(markerOptions);

    3、设置监听标记点击事件
    let callback = (marker: map.Marker) => {
      console.info(`on-markerClick marker = ${marker.getId()}`);
    };
    this.mapEventManager.on("markerClick", callback);
    4、设置监听标记拖动事件

    将Marker的拖拽属性设置为true,然后调用on(type: 'markerDragStart' , callback: Callback<Marker>)方法监听标记是否开始拖拽。

    调用on(type: 'markerDrag' , callback: Callback<Marker>),监听标记拖动过程。

    调用on(type: 'markerDragEnd' , callback: Callback<Marker>),监听标记拖动结束事件。

    // 设置标记可拖拽
    this.marker.setDraggable(true);
    
    // 监听标记开始拖拽
    let markerCallback = (marker: map.Marker) => {
      console.info(`on-markerDragStart marker = ${marker.getId()}`);
    };
    this.mapEventManager.on("markerDragStart", markerCallback);
    
    // 监听标记拖拽事件
    let markerDragCallback = (marker: map.Marker) => {
      console.info(`on-markerDrag marker = ${marker.getId()}`);
    };
    this.mapEventManager.on("markerDrag", markerDragCallback);
    
    // 监听标记拖拽结束
    let markerDragEndCallback = (marker: map.Marker) => {
      console.info(`on-markerDragEnd marker = ${marker.getId()}`);
    };
    this.mapEventManager.on("markerDragEnd", markerDragEndCallback);
    5、信息窗
    // 添加信息窗
    let markerOptions: mapCommon.MarkerOptions = {
      position: {
        latitude: 31.984410259206815,
        longitude: 118.76625379397866
      }
    };
    this.marker = await this.mapController?.addMarker(markerOptions);
    // 设置信息窗的标题
    this.marker.setTitle('南京');
    // 设置信息窗的子标题
    this.marker.setSnippet('华东地区');
    // 设置标记可点击
    this.marker.setClickable(true);
    // 设置信息窗的锚点位置
    this.marker.setInfoWindowAnchor(1, 1);
    // 设置信息窗可见
    this.marker.setInfoWindowVisible(true);
     
    6、自定义信息窗
    import { map, mapCommon, MapComponent } from '@kit.MapKit'
    import { AsyncCallback } from '@kit.BasicServicesKit'
    
    @Entry
    @Component
    struct MarkerDemo {
      private TAG = "OHMapSDK_MarkerDemo";
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        this.mapOptions = {
          position: {
            target: {
              latitude: 32.120750,
              longitude: 118.788765
            },
            zoom: 15
          }
        }
    
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
            let markerOptions: mapCommon.MarkerOptions = {
              position: {
                latitude: 32.120750,
                longitude: 118.788765
              },
              clickable: true,
              // 设置信息窗标题
              title: "自定义信息窗",
            };
            await this.mapController?.addMarker(markerOptions);
          }
        }
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({
              mapOptions: this.mapOptions,
              mapCallback: this.callback,
              // 自定义信息窗
              customInfoWindow: this.customInfoWindow
            })
              .width('100%')
              .height('100%');
          }.width('100%')
        }.height('100%')
      }
      // 自定义信息窗BuilderParam
      @BuilderParam customInfoWindow: ($$: map.MarkerDelegate) => void = this.customInfoWindowBuilder;
      // 自定义信息窗Builder
      @Builder
      customInfoWindowBuilder($$: map.MarkerDelegate) {
        if ($$.marker) {
          Text($$.marker.getTitle())
            .width("50%")
            .height(50)
            .backgroundColor(Color.Green)
            .textAlign(TextAlign.Center)
            .fontColor(Color.Black)
            .font({ size: 25, weight: 10, style: FontStyle.Italic })
            .border({ width: 3, color: Color.Black, radius: 25, style: BorderStyle.Dashed })
    
        }
      }
    }
     
    7、标记动画

    Marker支持设置旋转、缩放、平移、透明、图片动画播放和组合动画效果。

    接口名

    描述

    AlphaAnimation

    控制透明度的动画类。

    RotateAnimation

    控制旋转的动画类。

    ScaleAnimation

    控制缩放的动画类。

    TranslateAnimation

    控制平移的动画类。

    PlayImageAnimation

    控制多张图片的动画类。

    AnimationSet

    动画集合。

    旋转动画效果的示例代码如下:

    import { map, mapCommon, MapComponent } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';
    
    @Entry
    @Component
    struct MarkerDemo {
      private mapOptions?: mapCommon.MapOptions;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        this.mapOptions = {
          position: {
            target: {
              latitude: 32.020750,
              longitude: 118.788765
            },
            zoom: 11
          }
        }
    
        this.callback = async (err, mapController) => {
          if (!err) {
            // 构造MarkerOptions对象
            let markerOptions: mapCommon.MarkerOptions = {
              position: {
                latitude: 32.020750,
                longitude: 118.788765
              },
            };
            // 新建marker
            let marker: map.Marker = await mapController.addMarker(markerOptions);
            // 构造RotateAnimation对象
            let animation = new map.RotateAnimation(0, 270);
            // 动画执行时间
            animation.setDuration(2000);
    
            // 动画结束状态
            animation.setFillMode(map.AnimationFillMode.BACKWARDS);
    
            // 动画重复模式
            animation.setRepeatMode(map.AnimationRepeatMode.REVERSE);
    
            // 动画重复次数
            animation.setRepeatCount(100);
    
            // 设置动画开始监听
            let callbackStart = () => {
              console.info("animationStart", `callback`);
            };
            animation.on("animationStart", callbackStart);
    
            // 设置动画结束监听
            let callbackEnd = () => {
              console.info("animationEnd", `callback`);
            };
            animation.on("animationEnd", callbackEnd);
    
            // 设置动画
            marker.setAnimation(animation);
            // 开启动画
            marker.startAnimation();
          }
        }
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback })
          }.width('100%')
        }.height('100%')
      }
    }

    展示效果如图:

    8、图片动画播放
    import { map, mapCommon, MapComponent } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';
    import { image } from '@kit.ImageKit';
    
    @Entry
    @Component
    struct MarkerDemo {
      private mapOptions?: mapCommon.MapOptions;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        this.mapOptions = {
          position: {
            target: {
              latitude: 32.020750,
              longitude: 118.788765
            },
            zoom: 11
          }
        }
    
        this.callback = async (err, mapController) => {
          if (!err) {
            // 构造MarkerOptions对象
            let markerOptions: mapCommon.MarkerOptions = {
              position: {
                latitude: 32.020750,
                longitude: 118.788765
              },
            };
            let mContext = getContext();
            const fileData: Uint8Array = await mContext?.resourceManager?.getRawFileContent('icon/icon.png');
            let imageSource: image.ImageSource =
              image.createImageSource(fileData.buffer.slice(0, fileData.buffer.byteLength));
            let pixelMap: PixelMap = await imageSource.createPixelMap();
            let images: Array<ResourceStr | image.PixelMap> = [
            // 图标需存放在resources/rawfile
              'icon/avocado.png',
              'icon/20231027.png',
              pixelMap,
              $r('app.media.maps_blue_dot')
            ]
            // 新建marker
            let marker: map.Marker = await mapController.addMarker(markerOptions);
            // 构造PlayImageAnimation对象
            let animation: map.PlayImageAnimation = new map.PlayImageAnimation();
            // 添加图片
            await animation.addImages(images)
            // 动画执行时间
            animation.setDuration(3000);
    
            // 动画结束状态
            animation.setFillMode(map.AnimationFillMode.BACKWARDS);
    
            // 动画重复模式
            animation.setRepeatMode(map.AnimationRepeatMode.REVERSE);
    
            // 动画重复次数
            animation.setRepeatCount(100);
    
            // 设置动画开始监听
            let callbackStart = () => {
              console.info("animationStart", `callback`);
            };
            animation.on("animationStart", callbackStart);
            // 设置动画结束监听
            let callbackEnd = () => {
              console.info("animationEnd", `callback`);
            };
            animation.on("animationEnd", callbackEnd);
            // 设置动画
            marker.setAnimation(animation);
            // 开启动画
            marker.startAnimation();
          }
        }
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback })
          }.width('100%')
        }.height('100%')
      }
    }

    展示效果如图:

     5.2 折线

    地图上绘制折线、设置折线分段颜色、设置折线可渐变、绘制纹理。

    5.2.1 接口说明

    添加折线功能主要由MapPolylineOptions、addPolyline和MapPolyline提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    MapPolylineOptions

    折线参数。

    addPolyline(options: mapCommon.MapPolylineOptions): Promise<MapPolyline>

    在地图上添加一条折线。

    MapPolyline

    折线,支持更新和查询相关属性。

    5.2.2 开发步骤

    1、添加折线

            1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

            2. 添加折线,在Callback方法中创建初始化参数并新建MapPolyline。

    @Entry
    @Component
    struct MapPolylineDemo {
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
      private mapPolyline?: map.MapPolyline;
    
      aboutToAppear(): void {
        // 地图初始化参数
        this.mapOptions = {
          position: {
            target: {
              latitude: 31.98,
              longitude: 118.78
            },
            zoom: 14
          }
        };
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
    
            // polyline初始化参数
            let polylineOption: mapCommon.MapPolylineOptions = {
              points: [{longitude:118.78,latitude:31.975}, {longitude:118.78,latitude:31.982}, {longitude:118.79,latitude:31.985}],
              clickable: true,
              startCap: mapCommon.CapStyle.BUTT,
              endCap: mapCommon.CapStyle.BUTT,
              geodesic: false,
              jointType: mapCommon.JointType.BEVEL,
              visible: true,
              width: 10,
              zIndex: 10,
              gradient: false
            }
            // 创建polyline
            this.mapPolyline = await this.mapController.addPolyline(polylineOption);
          }
        };
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
          }.width('100%')
        }.height('100%')
      }
    }

     

    2、设置折线分段颜色

    方法一:新建折线时在MapPolylineOptions的colors属性中设置折线分段颜色值。

    let polylineOption: mapCommon.MapPolylineOptions = {
      ...
      colors: [0xffffff00, 0xff000000]
    };

     方法二:调用MapPolyline的setColors()方法。

    let colors = [0xffffff00, 0xff000000];
    this.mapPolyline.setColors(colors);

    3、设置折线可渐变

    方法一:MapPolylineOptions的gradient属性设置为true。

    let polylineOption: mapCommon.MapPolylineOptions = {
      ...
      gradient: true
    };

    方法二:调用MapPolyline的setGradient()方法。

    this.mapPolyline.setGradient(true);

     

    4、绘制纹理

    方法一:新建折线时在MapPolylineOptions的customTexture属性设置折线纹理。

    let polylineOption: mapCommon.MapPolylineOptions = {
      points: [
        { latitude: 32.220750, longitude: 118.788765 },
        { latitude: 32.120750, longitude: 118.788765 },
        { latitude: 32.020750, longitude: 118.788765 },
        { latitude: 31.920750, longitude: 118.788765 },
        { latitude: 31.820750, longitude: 118.788765 },
      ],
      clickable: true,
      jointType: mapCommon.JointType.DEFAULT,
      width: 20,
      customTexture: "icon/naviline_arrow.png"
    }

     方法二:调用MapPolyline的setCustomTexture方法。

    await this.mapPolyline.setCustomTexture("icon/naviline_arrow.png");

    5.3 弧线

    在地图上绘制弧线,通过MapArcParams类设置弧线的位置、宽度、颜色等参数。 

    5.3.1 接口说明

    添加弧线功能主要由MapArcParams、addArc和MapArc提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    MapArcParams

    弧线参数。

    addArc(params: mapCommon.MapArcParams): MapArc

    添加一条弧线。

    MapArc

    弧线,支持更新和查询相关属性。

    5.3.2 开发步骤

    1、添加弧线

            1. 导入相关模块。

    import { map, mapCommon, MapComponent } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

            2. 添加弧线,在Callback方法中创建初始化参数并新建MapArc。

    @Entry
    @Component
    struct MapArcDemo {
      private TAG = "OHMapSDK_MapArcDemo";
      private mapOptions?: mapCommon.MapOptions;
      private mapController?: map.MapComponentController;
      private callback?: AsyncCallback<map.MapComponentController>;
    
      aboutToAppear(): void {
        this.mapOptions = {
          position: {
            target: {
              latitude: 34.757975,
              longitude: 113.665412
            },
            zoom: 6
          },
        }
    
        this.callback = async (err, mapController) => {
          if (!err) {
            this.mapController = mapController;
            if (!this.mapController) {
              console.info(this.TAG, "mapController is null1");
              return;
            }
            // 设置弧线参数
            let mapArcParams: mapCommon.MapArcParams = {
              // 弧线起点坐标
              startPoint: {
                latitude: 39.913138,
                longitude: 116.415112
              },
              // 弧线终点坐标
              endPoint: {
                latitude: 28.239473,
                longitude: 112.954094
              },
              // 弧线中心点坐标
              centerPoint: {
                latitude: 33.86970399048567,
                longitude: 112.08633528544145
              },
              width: 10,
              color: 0xffff0000,
              visible: true,
              zIndex: 100
            };
            // 添加弧线
            this.mapController.addArc(mapArcParams);
          }
        }
      }
    
      build() {
        Stack() {
          Column() {
            MapComponent({
              mapOptions: this.mapOptions,
              mapCallback: this.callback,
            })
              .width('100%')
              .height('100%');
          }.width('100%')
        }.height('100%')
      }
    }

     5.4 多边形

    在地图上绘制多边形。

    5.4.1 接口说明

    添加多边形功能主要由MapPolygonOptions、addPolygon和MapPolygon提供,更多接口及使用方法请参见接口文档。

    接口名

    描述

    MapPolygonOptions

    多边形参数。

    addPolygon(options: mapCommon.MapPolygonOptions): Promise<MapPolygon>

    在地图上添加一个多边形。

    MapPolygon

    多边形,支持更新和查询相关属性。

    5.4.2 开发步骤

            1. 导入相关模块。

    import { MapComponent, mapCommon, map } from '@kit.MapKit';
    import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 添加多边形,在Callback方法中创建初始化参数并新建polygon。

      @Entry
      @Component
      struct MapPolygonDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private mapPolygon?: map.MapPolygon;
      
        aboutToAppear(): void {
          // 地图初始化参数
          this.mapOptions = {
            position: {
              target: {
                latitude: 31.98,
                longitude: 118.78
              },
              zoom: 14
            }
          };
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
              // 多边形初始化参数
              let polygonOptions: mapCommon.MapPolygonOptions = {
                  points: [{longitude:118.78,latitude:31.975}, {longitude:118.78,latitude:31.985}, 
                           {longitude:118.79,latitude:31.985},{longitude:118.79,latitude:31.975}], 
                  clickable: true,
                  fillColor: 0xff00DE00,
                  geodesic: false,
                  strokeColor: 0xff000000,
                  jointType: mapCommon.JointType.DEFAULT,
                  strokeWidth: 10,
                  visible: true,
                  zIndex: 10
                }
              // 创建多边形
              this.mapPolygon = await this.mapController.addPolygon(polygonOptions);
            }
          };
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
            }.width('100%')
          }.height('100%')
        }
      }

      5.5 圆形

       在地图上绘制圆形。

      5.5.1 接口说明

      添加圆形功能主要由MapCircleOptions、addCircle和MapCircle提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      MapCircleOptions

      圆形参数。

      addCircle(options: mapCommon.MapCircleOptions): Promise<MapCircle>

      在地图上添加一个圆,指定圆心经纬度和圆的半径,用于表示某个位置的周边范围。

      MapCircle

      圆形,支持更新和查询相关属性。

      5.5.2 开发步骤

              1. 导入相关模块。

      import { MapComponent, mapCommon, map } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 添加圆,在Callback方法中创建初始化参数并新建Circle。

      @Entry
      @Component
      struct MapCircleDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private mapCircle?: map.MapCircle;
      
        aboutToAppear(): void {
          // 地图初始化参数
          this.mapOptions = {
            position: {
              target: {
                 latitude: 39.918,
                 longitude: 116.397
              },
              zoom: 14
            }
          };
      
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
              // Circle初始化参数
              let mapCircleOptions: mapCommon.MapCircleOptions = {
                center: {
                   latitude: 39.918,
                   longitude: 116.397
                },
                radius: 500,
                clickable: true,
                fillColor: 0XFFFFC100,
                strokeColor: 0xFFFF0000,
                strokeWidth: 10,
                visible: true,
                zIndex: 15
              }
              // 创建Circle
              this.mapCircle = await this.mapController.addCircle(mapCircleOptions);
            }
          };
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
            }.width('100%')
          }.height('100%')
        }
      }

       5.6 点注释

      在地图的指定位置添加点注释以标识位置、商家、建筑等,并可以通过信息窗口展示详细信息。

      点注释支持功能:

      • 支持设置图标、文字、碰撞规则等。
      • 支持添加点击事件。

      PointAnnotation有默认风格,同时也支持自定义。由于内容丰富.

      5.6.1 接口说明

      添加点注释功能主要由PointAnnotationParams、addPointAnnotation、PointAnnotation、on、off提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      PointAnnotationParams

      点注释参数。

      addPointAnnotation(params: mapCommon.PointAnnotationParams): Promise<PointAnnotation>

      在地图上添加点注释。

      PointAnnotation

      点注释,支持更新和查询相关属性。

      on(type: 'pointAnnotationClick', callback: Callback<PointAnnotation>): void

      设置点注释点击事件监听器。

      off(type: 'pointAnnotationClick', callback: Callback<PointAnnotation>): void

      取消监听点注释点击事件。

      5.6.2 开发步骤

      1、添加点注释

              1. 导入相关模块

      import { MapComponent, mapCommon, map } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 添加点注释,在Callback方法中创建初始化参数并新建点注释。

      @Entry
      @Component
      struct PointAnnotationDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private pointAnnotation?: map.PointAnnotation;
      
        aboutToAppear(): void {
          this.mapOptions = {
            position: {
              target: {
                  latitude: 32.020750,
                  longitude: 118.788765
              },
              zoom: 14
            }
          };
      
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
                let pointAnnotationOptions: mapCommon.PointAnnotationParams = {
                  // 定义点注释图标锚点
                  position: {
                    latitude: 32.020750,
                    longitude: 118.788765
                  },
                  // 定义点注释名称与地图poi名称相同时,是否支持去重
                  repeatable: true,
                  // 定义点注释的碰撞规则
                  collisionRule: mapCommon.CollisionRule.NAME,
                  // 定义点注释的标题,数组长度最小为1,最大为3
                  titles: [{
                    // 定义标题内容
                    content: "南京夫子庙",
                    // 定义标题字体颜色
                    color: 0xFF000000,
                    // 定义标题字体大小
                    fontSize: 15,
                    // 定义标题描边颜色
                    strokeColor: 0xFFFFFFFF,
                    // 定义标题描边宽度
                    strokeWidth: 2,
                    // 定义标题字体样式
                    fontStyle: mapCommon.FontStyle.ITALIC
                  }
                  ],
                  // 定义点注释的图标,图标存放在resources/rawfile
                  icon: "",
                  // 定义点注释是否展示图标
                  showIcon: true,
                  // 定义点注释的锚点在水平方向上的位置
                  anchorU: 0.5,
                  // 定义点注释的锚点在垂直方向上的位置
                  anchorV: 1,
                  // 定义点注释的显示属性,为true时,在被碰撞后仍能显示
                  forceVisible: false,
                  // 定义碰撞优先级,数值越大,优先级越低
                  priority: 3,
                  // 定义点注释展示的最小层级
                  minZoom: 2,
                  // 定义点注释展示的最大层级
                  maxZoom: 20,
                  // 定义点注释是否可见
                  visible: true,
                  // 定义点注释叠加层级属性
                  zIndex: 10
                }
              this.pointAnnotation = await this.mapController.addPointAnnotation(pointAnnotationOptions);
            }
          };
        }
        build() {
          Stack() {
            Column() {
              MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
            }.width('100%')
          }.height('100%')
        }
      }

               3. 在添加点注释之后,修改已经设置的点注释属性。

      // 设置点注释的显示层级为3~14级
      this.pointAnnotation.setZoom(3,14);
      // 设置点注释的碰撞优先级为10
      this.pointAnnotation.setPriority(10);
      2、设置监听点注释点击事件
      let callback = (pointAnnotation: map.PointAnnotation) => {
        console.info("pointAnnotationClick", `pointAnnotationClick: ${pointAnnotation.getId()}`);
      };
      this.mapEventManager.on("pointAnnotationClick", callback);
       3、点注释动画

      PointAnnotation调用setAnimation(animation: Animation)设置动画。

      PointAnnotation调用startAnimation启动动画。

      let animation: map.ScaleAnimation = new map.ScaleAnimation(1, 3, 1, 3);
      // 设置动画单次的时长
      animation.setDuration(3000);
      // 设置动画开始监听
      let callbackStart = () => {
        console.info("animationStart", `callback`);
      };
      animation.on("animationStart", callbackStart);
      // 设置动画结束监听
      let callbackEnd = () => {
        console.info("animationEnd", `callback`);
      };
      animation.on("animationEnd", callbackEnd);
      // 设置动画执行完成的状态
      animation.setFillMode(map.AnimationFillMode.BACKWARDS);
      // 设置动画重复的方式
      animation.setRepeatMode(map.AnimationRepeatMode.REVERSE);
      // 设置动画插值器
      animation.setInterpolator(Curve.Linear);
      // 设置动画的重复次数
      animation.setRepeatCount(100);
      this.pointAnnotation.setAnimation(animation);
      this.pointAnnotation.startAnimation();

       

      4、点注释标题动画 

      PointAnnotation调用setTitleAnimation(animation:FontSizeAnimation )设置标题动画。

      PointAnnotation调用startTitleAnimation启动标题动画。

      let animation: map.FontSizeAnimation = new map.FontSizeAnimation(15, 45);
      // 设置动画单次的时长
      animation.setDuration(3000);
      // 设置动画开始监听
      let callbackStart = () => {
        console.info("animationStart", `callback`);
      };
      animation.on("animationStart", callbackStart);
      // 设置动画结束监听
      let callbackEnd = () => {
        console.info("animationEnd", `callback`);
      };
      animation.on("animationEnd", callbackEnd);
      // 设置动画执行完成的状态
      animation.setFillMode(map.AnimationFillMode.FORWARDS);
      // 设置动画重复的方式
      animation.setRepeatMode(map.AnimationRepeatMode.REVERSE);
      // 设置动画插值器
      animation.setInterpolator(Curve.Linear);
      // 设置动画的重复次数
      animation.setRepeatCount(100);
      this.pointAnnotation.setTitleAnimation(animation);
      this.pointAnnotation.startTitleAnimation();

      5.7 气泡

      通过气泡在道路上指定位置显示测速、拥堵情况。气泡支持功能:

      • 支持设置四个方向的图标(传入的图标宽高需要相同)。
      • 支持设置图标碰撞规则。
      • 支持设置当前气泡的候选坐标段,通过计算使气泡在最佳的线段位置上。
      • 支持设置图标动画。
      • 支持添加点击事件。

      5.7.1 接口说明

      添加气泡功能主要由BubbleParams、addBubble和Bubble提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      BubbleParams

      气泡参数。

      addBubble(params: mapCommon.BubbleParams): Promise<Bubble>

      在地图上添加气泡。

      Bubble

      气泡,支持更新和查询相关属性。

      5.7.2 开发步骤

      1、添加气泡

              1. 导入相关模块。

      import { MapComponent, mapCommon, map } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 添加气泡,在Callback方法中创建初始化参数并新建气泡。

      @Entry
      @Component
      struct BubbleDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private bubble?: map.Bubble;
      
        aboutToAppear(): void {
          this.mapOptions = {
            position: {
              target: {
                  latitude: 39.918,
                  longitude: 116.397
              },
              zoom: 14
            }
          };
      
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
              let bubbleOptions: mapCommon.BubbleParams = {
                 // 气泡位置
                 positions: [[{ latitude: 39.918, longitude: 116.397 }]],
                 // 设置图标,必须提供4个方向的图标,图标存放在resources/rawfile
                 icons: [
                    'speed_limit_10.png',
                    'speed_limit_20.png',
                    'speed_limit_30.png',
                    'speed_limit_40.png'
                 ],
                 // 定义气泡的显示属性,为true时,在被碰撞后仍能显示
                 forceVisible: true,
                 // 定义气泡碰撞优先级,数值越大,优先级越低
                 priority: 3,
                 // 定义气泡展示的最小层级
                 minZoom: 2,
                 // 定义气泡展示的最大层级
                 maxZoom: 20,
                 // 定义气泡是否可见
                 visible: true,
                 // 定义气泡叠加层级属性
                 zIndex: 1
              }
              // 添加气泡
              this.bubble = await this.mapController.addBubble(bubbleOptions);
            }
          };
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
            }.width('100%')
          }.height('100%')
        }
      }

      2、设置监听气泡点击事件
      this.mapController?.on("bubbleClick", (bubble) => {
        console.info(`on-BubbleClick bubble = ${bubble.getId()}`);
      });
      3、气泡动画

      Bubble调用setAnimation(animation: Animation)设置动画。

      Bubble调用startAnimation启动动画。

      let animation: map.ScaleAnimation = new map.ScaleAnimation(1, 3, 1, 3);
      // 设置动画单次的时长
      animation.setDuration(3000);
      // 设置动画开始监听
      let callbackStart = () => {
        console.info("animationStart", `callback`);
      };
      animation.on("animationStart", callbackStart);
      // 设置动画结束监听
      let callbackEnd = () => {
        console.info("animationEnd", `callback`);
      };
      animation.on("animationEnd", callbackEnd);
      // 设置动画执行完成的状态
      animation.setFillMode(map.AnimationFillMode.BACKWARDS);
      // 设置动画重复的方式
      animation.setRepeatMode(map.AnimationRepeatMode.REVERSE);
      // 设置动画插值器
      animation.setInterpolator(Curve.Linear);
      // 设置动画的重复次数
      animation.setRepeatCount(100);
      this.bubble.setAnimation(animation);
      this.bubble.startAnimation();

      5.8 点聚合

      通过比例尺缩放自适应聚合效果,聚合图标可点击。聚合支持功能:

      • 支持按距离聚合ClusterItem。
      • 支持绘制聚合Overlay的默认图标。
      • 支持绘制聚合Overlay的自定义图标。
      • 支持监听聚合Overlay的点击事件。
      • 支持添加单个ClusterItem到聚合Overlay中。
      • 支持删除聚合Overlay。
      • 支持移动地图时重绘聚合Overlay。

      5.8.1 接口说明

      聚合功能主要由ClusterOverlayParams、addClusterOverlay、ClusterOverlay提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      ClusterOverlayParams

      点聚合参数。

      addClusterOverlay(params: mapCommon.ClusterOverlayParams): Promise<ClusterOverlay>

      聚合接口,支持节点聚合能力。

      ClusterOverlay

      点聚合,支持更新和查询相关属性。

      5.8.2 开发步骤

              1 导入相关模块。

      import { map, mapCommon, MapComponent } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 新增聚合图层。

      @Entry
      @Component
      struct ClusterOverlayDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
      
        aboutToAppear(): void {
          this.mapOptions = {
            position: {
              target: {
                latitude: 31.98,
                longitude: 118.7
              },
              zoom: 7
            }
          }
      
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
              // 生成待聚合点
              let clusterItem1: mapCommon.ClusterItem = {
                position: {
                  latitude: 31.98,
                  longitude: 118.7
                }
              };
              let clusterItem2: mapCommon.ClusterItem = {
                position: {
                  latitude: 32.99,
                  longitude: 118.9
                }
              };
              let clusterItem3: mapCommon.ClusterItem = {
                position: {
                  latitude: 31.5,
                  longitude: 118.7
                }
              };
              let clusterItem4: mapCommon.ClusterItem = {
                position: {
                  latitude: 30,
                  longitude: 118.7
                }
              };
              let clusterItem5: mapCommon.ClusterItem = {
                position: {
                  latitude: 29.98,
                  longitude: 117.7
                }
              };
              let clusterItem6: mapCommon.ClusterItem = {
                position: {
                  latitude: 31.98,
                  longitude: 120.7
                }
              };
              let clusterItem7: mapCommon.ClusterItem = {
                position: {
                  latitude: 25.98,
                  longitude: 119.7
                }
              };
              let clusterItem8: mapCommon.ClusterItem = {
                position: {
                  latitude: 30.98,
                  longitude: 110.7
                }
              };
              let clusterItem9: mapCommon.ClusterItem = {
                position: {
                  latitude: 30.98,
                  longitude: 115.7
                }
              };
              let clusterItem10: mapCommon.ClusterItem = {
                position: {
                  latitude: 28.98,
                  longitude: 122.7
                }
              };
              let array: Array<mapCommon.ClusterItem> = [
                clusterItem1,
                clusterItem2,
                clusterItem3,
                clusterItem4,
                clusterItem5,
                clusterItem6,
                clusterItem7,
                clusterItem8,
                clusterItem9,
                clusterItem10
              ]
              for(let index = 0; index < 100; index++){
                array.push(clusterItem1)
              }
              for(let index = 0; index < 10; index++){
                array.push(clusterItem2)
              }
              // 生成聚合图层的入参 聚合distance设置为100vp
              let clusterOverlayParams: mapCommon.ClusterOverlayParams = { distance: 100, clusterItems: array };
              // 调用addClusterOverlay生成聚合图层
              await this.mapController.addClusterOverlay(clusterOverlayParams);
      
            }
          }
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback })
                .width('100%')
                .height('100%');
            }.width('100%')
          }.height('100%')
        }
      }

      5.9 覆盖物

      地图覆盖物是固定在地图上的图片,本章节将向您介绍如何为地图增加覆盖物。

      覆盖物,是一种位于底图和底图标注层之间的特殊Overlay,该图层不会遮挡地图标注信息。通过ImageOverlayParams类来设置,开发者可以通过ImageOverlayParams类设置一张图片,该图片可随地图的平移、缩放、旋转等操作做相应的变换。

      5.9.1 接口说明

      增加覆盖物功能主要由ImageOverlayParams、addImageOverlay、ImageOverlay提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      ImageOverlayParams

      覆盖物参数。

      addImageOverlay(params: mapCommon.ImageOverlayParams): Promise<ImageOverlay>

      为地图增加覆盖物。

      ImageOverlay

      覆盖物,支持更新和查询相关属性。

      5.9.2 开发步骤

              1. 导入相关模块。

      import { map, mapCommon, MapComponent } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 增加覆盖物。

      @Entry
      @Component
      struct ImageOverlayDemo {
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private mapEventManager?: map.MapEventManager;
      
        aboutToAppear(): void {
          this.mapOptions = {
            position: {
              target: {
                latitude: 32.2,
                longitude: 118.2
              },
              zoom: 10
            }
          }
      
          this.callback = async (err, mapController) => {
            if (!err) {
              this.mapController = mapController;
              this.mapEventManager = this.mapController.getEventManager();
              let imageOverlayParams: mapCommon.ImageOverlayParams = {
                // 覆盖物范围
                bounds: {
                  southwest: { latitude: 32, longitude: 118 },
                  northeast: { latitude: 32.4, longitude: 118.4 }
                },
                // 覆盖物图片
                image: 'icon/icon.png',
                transparency: 0.3,
                zIndex: 101,
                anchorU: 0.5,
                anchorV: 0.5,
                clickable: true,
                visible: true,
                bearing: 0
              };
              // 添加覆盖物
              let imageOverlay = await this.mapController?.addImageOverlay(imageOverlayParams);
            }
          }
        }
        build() {
          Stack() {
            Column() {
              MapComponent({
                mapOptions: this.mapOptions,
                mapCallback: this.callback,
              })
                .width('100%')
                .height('100%');
            }.width('100%')
          }.height('100%')
        }
      }

              3. 设置覆盖物点击监听事件。

      let imageOverlayCallback: Callback<map.ImageOverlay> = (imageOverlay: map.ImageOverlay) => {
        console.info("imageOverlay callback");
      }
      // 打开覆盖物的点击监听
      this.mapEventManager.on("imageOverlayClick", imageOverlayCallback)
      // 关闭覆盖物的点击监听
      this.mapEventManager.off("imageOverlayClick", imageOverlayCallback);

       5.10 3D建筑

      在地图上绘制3D建筑。

      5.10.1 接口说明

      添加3D建筑功能主要由BuildingOverlayParams、addBuildingOverlay和BuildingOverlay提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      BuildingOverlayParams

      3D建筑参数。

      addBuildingOverlay(params: mapCommon.BuildingOverlayParams): Promise<BuildingOverlay>

      在地图上添加3D建筑。

      BuildingOverlay

      3D建筑,支持更新和查询相关属性。

      5.10.2 开发步骤

      1、添加3D建筑

              1. 导入相关模块。

      import { mapCommon, map, MapComponent } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 添加3D建筑。

      @Entry
      @Component
      struct BuildingOverlayDemo {
        private TAG = "OHMapSDK_BuildingOverlayDemo";
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
        private buildingOverlay?: map.BuildingOverlay;
      
        aboutToAppear(): void {
          // 初始化地图参数
          this.mapOptions = {
            position: {
              target: {
                latitude: 31.984794,
                longitude: 118.765865
              },
              zoom: 18
            },
            scaleControlsEnabled: true
          }
      
          this.callback = async (err, mapController) => {
            console.info(this.TAG, "addBuildingOverlay");
            if (!err) {
              this.mapController = mapController;
              let points: Array<mapCommon.LatLng> = [
                {
                  latitude: 31.984794,
                  longitude: 118.765865
                },
                {
                  latitude: 31.98468,
                  longitude: 118.766076
                },
                {
                  latitude: 31.98472,
                  longitude: 118.766116
                },
                {
                  latitude: 31.98463,
                  longitude: 118.766292
                },
                {
                  latitude: 31.984586,
                  longitude: 118.766251
                },
                {
                  latitude: 31.984536,
                  longitude: 118.766344
                },
                {
                  latitude: 31.984633,
                  longitude: 118.766446
                },
                {
                  latitude: 31.9848,
                  longitude: 118.766285
                },
                {
                  latitude: 31.984925,
                  longitude: 118.766312
                },
                {
                  latitude: 31.985282,
                  longitude: 118.766661
                },
                {
                  latitude: 31.985438,
                  longitude: 118.766419
                },
                {
                  latitude: 31.985801,
                  longitude: 118.766755
                },
                {
                  latitude: 31.985856,
                  longitude: 118.766504
                },
                {
                  latitude: 31.985785,
                  longitude: 118.766434
                },
                {
                  latitude: 31.985821,
                  longitude: 118.766278
                },
                {
                  latitude: 31.985897,
                  longitude: 118.766311
                },
                {
                  latitude: 31.985944,
                  longitude: 118.766095
                },
                {
                  latitude: 31.985909,
                  longitude: 118.766069
                },
                {
                  latitude: 31.985794,
                  longitude: 118.765989
                },
                {
                  latitude: 31.9857,
                  longitude: 118.766029
                },
                {
                  latitude: 31.985658,
                  longitude: 118.766164
                },
                {
                  latitude: 31.985647,
                  longitude: 118.766271
                },
                {
                  latitude: 31.985574,
                  longitude: 118.766297
                },
                {
                  latitude: 31.985458,
                  longitude: 118.766285
                },
                {
                  latitude: 31.985271,
                  longitude: 118.766002
                },
                {
                  latitude: 31.985219,
                  longitude: 118.766002
                },
                {
                  latitude: 31.985135,
                  longitude: 118.766029
                },
                {
                  latitude: 31.985093,
                  longitude: 118.766083
                },
                {
                  latitude: 31.985019,
                  longitude: 118.766109
                },
                {
                  latitude: 31.984978,
                  longitude: 118.766083
                },
                {
                  latitude: 31.984794,
                  longitude: 118.765865
                }
              ];
              points.reverse();
              // 3D建筑参数
              let buildingOverlayOptions: mapCommon.BuildingOverlayParams =
                {
                  // 3D建筑的范围参数(点为顺时针绘制)
                  points: points,
                  // 3D建筑的高度
                  totalHeight: 51,
                  // 3D建筑的选中楼层高度
                  floorBottomHeight: 33,
                  // 3D建筑的顶部颜色
                  topFaceColor: 0xffa4b8f7,
                  // 3D建筑的侧面颜色
                  sideFaceColor: 0x44a4b8f7,
                  // 3D建筑的选中楼层颜色
                  floorColor: 0xff000000,
                  // 3D建筑的展示层级
                  showLevel: 14,
                  // 3D建筑选中楼层从底部升起的动画时长
                  animationDuration: 5000,
                  // 3D建筑侧面的纹理
                  sideTexture: { image: $r("app.media.side_tex"), height: 3, width: 3 },
                  // 3D建筑选中楼层的纹理
                  floorTexture: { image: $r("app.media.floor_tex"), height: 3, width: 3 }
                }
              let cameraUpdate = map.newCameraPosition({
                target: {
                  latitude: 31.984794,
                  longitude: 118.765865
                },
                zoom: 18, tilt: 70
              });
              // 将地图镜头移动到3D建筑区域
              this.mapController?.moveCamera(cameraUpdate);
              // 新建3D建筑
              this.buildingOverlay = await this.mapController?.addBuildingOverlay(buildingOverlayOptions);
            }
          }
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({
                mapOptions: this.mapOptions,
                mapCallback: this.callback,
              }).width('100%').height('100%');
            }.width('100%')
          }.height('100%')
        }
      }

       5.11 动态轨迹

      在地图上绘制动态轨迹。

      5.11.1 接口说明

      绘制动态轨迹功能主要由TraceOverlayParams、addTraceOverlay、Marker和TraceOverlay提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      TraceOverlayParams

      动态轨迹参数。

      addTraceOverlay(params: mapCommon.TraceOverlayParams, markers?: Array<Marker>): Promise<TraceOverlay>

      绘制动态轨迹。

      Marker

      动态轨迹的一组标记。

      TraceOverlay

      动态轨迹,支持暂停和删除等功能。

      5.11.2 开发步骤

              1. 导入相关模块

      import { mapCommon, map, MapComponent } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

              2. 绘制动态轨迹。

      @Entry
      @Component
      struct TranceOverLayDemo {
        private TAG = "OHMapSDK_TranceOverLayDemo";
        private mapOptions?: mapCommon.MapOptions;
        private mapController?: map.MapComponentController;
        private callback?: AsyncCallback<map.MapComponentController>;
      
        aboutToAppear(): void {
          // 初始化地图参数
          this.mapOptions = {
            position: {
              target: {
                latitude: 31.99227173519985,
                longitude: 118.7622219990476
              },
              zoom: 16
            },
            scaleControlsEnabled: true
          }
      
          this.callback = async (err, mapController) => {
            console.info(this.TAG, "mapCallback err=" + JSON.stringify(err) +
              "; mapController=" + JSON.stringify(mapController));
            if (!err) {
              this.mapController = mapController;
              // marker1的参数
              let markerOptions1: mapCommon.MarkerOptions = {
                position: {
                  latitude: 31.99227173519985,
                  longitude: 118.7622219990476
                },
                icon: $r("app.media.track_setting_sport_map_marker_22"),
                anchorU: 0.5,
                anchorV: 1,
                visible: true
              };
              // 新增marker1
              let markerBoy1 = await this.mapController.addMarker(markerOptions1);
              let boyImages1: map.PlayImageAnimation = new map.PlayImageAnimation();
              boyImages1.setDuration(1000);
              let resoureArray: Array<Resource> = new Array();
              // 需要替换您自己的资源图片,存放在resources/base/media目录下
              resoureArray.push($r("app.media.side_0"));
              resoureArray.push($r("app.media.side_1"));
              resoureArray.push($r("app.media.side_2"));
              resoureArray.push($r("app.media.side_3"));
              resoureArray.push($r("app.media.side_4"));
              resoureArray.push($r("app.media.side_5"));
              resoureArray.push($r("app.media.side_6"));
              resoureArray.push($r("app.media.side_7"));
              resoureArray.push($r("app.media.side_8"));
              resoureArray.push($r("app.media.side_9"));
              resoureArray.push($r("app.media.side_10"));
              resoureArray.push($r("app.media.side_11"));
              resoureArray.push($r("app.media.side_12"));
              resoureArray.push($r("app.media.side_13"));
              resoureArray.push($r("app.media.side_14"));
              resoureArray.push($r("app.media.side_15"));
              resoureArray.push($r("app.media.side_16"));
              resoureArray.push($r("app.media.side_17"));
              resoureArray.push($r("app.media.side_18"));
              resoureArray.push($r("app.media.side_19"));
              resoureArray.push($r("app.media.side_20"));
              await boyImages1.addImages(resoureArray);
              boyImages1.setRepeatCount(-1);
      
              // marker1添加动画
              markerBoy1.setAnimation(boyImages1);
              markerBoy1.startAnimation();
      
              // marker2的参数
              let markerOptions2: mapCommon.MarkerOptions = {
                position: {
                  latitude: 31.99227173519985,
                  longitude: 118.7622219990476
                },
                icon: $r("app.media.track_setting_sport_map_marker_22"),
                anchorU: 0.5,
                anchorV: 1,
                visible: false
              };
              // 新增marker2
              let markerBoy2 = await this.mapController.addMarker(markerOptions2)
              let boyImages2: map.PlayImageAnimation = new map.PlayImageAnimation();
              boyImages2.setDuration(1000);
              let resoureArray2: Array<Resource> = new Array();
              // 需要替换您自己的资源图片,存放在resources/base/media目录下
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_000"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_001"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_002"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_003"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_004"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_005"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_006"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_007"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_008"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_009"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_010"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_011"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_012"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_013"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_014"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_015"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_016"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_017"));
              resoureArray2.push($r("app.media.behavior_front_cycling_boy_018"));
              await boyImages2.addImages(resoureArray2);
              boyImages2.setRepeatCount(-1);
              // marker2添加动画
              markerBoy2.setAnimation(boyImages2);
              markerBoy2.startAnimation();
      
              let points: Array<mapCommon.LatLng> = new Array();
              points.push({ latitude: 31.99685233070878, longitude: 118.75846023442728 });
              points.push({ latitude: 31.99671325810786, longitude: 118.75846738985165 });
              points.push({ latitude: 31.99659191076709, longitude: 118.7585347621686 });
              points.push({ latitude: 31.99648202537233, longitude: 118.7586266510386 });
              points.push({ latitude: 31.99637707201552, longitude: 118.75872004590596 });
              points.push({ latitude: 31.996278207010903, longitude: 118.75880449946251 });
              points.push({ latitude: 31.996187481969695, longitude: 118.7588781960278 });
              points.push({ latitude: 31.996092248919354, longitude: 118.75895330554488 });
              points.push({ latitude: 31.995962740450565, longitude: 118.75904721407304 });
              points.push({ latitude: 31.995792921394, longitude: 118.75916904998051 });
              points.push({ latitude: 31.995601885713416, longitude: 118.7593235241019 });
              points.push({ latitude: 31.995398221178277, longitude: 118.75949998588176 });
              points.push({ latitude: 31.995185902197715, longitude: 118.7596871082939 });
              points.push({ latitude: 31.994983473052656, longitude: 118.75987334062296 });
              points.push({ latitude: 31.99482433699269, longitude: 118.76002095184032 });
              points.push({ latitude: 31.994709073721708, longitude: 118.76012902920532 });
              points.push({ latitude: 31.99460732100702, longitude: 118.76023892576234 });
              points.push({ latitude: 31.99449284962087, longitude: 118.7603694232856 });
              points.push({ latitude: 31.99435358179254, longitude: 118.76053622438056 });
              points.push({ latitude: 31.99420771148339, longitude: 118.76072790126692 });
              points.push({ latitude: 31.994075194901523, longitude: 118.7609100960977 });
              points.push({ latitude: 31.993952686158877, longitude: 118.7610741329013 });
              points.push({ latitude: 31.993840180644217, longitude: 118.7612193418965 });
              points.push({ latitude: 31.993733787150244, longitude: 118.76135383115654 });
              points.push({ latitude: 31.993617206525155, longitude: 118.76150529647698 });
      
              // 动态轨迹的入参
              let tranceOptions: mapCommon.TraceOverlayParams = {
                // 轨迹点
                points: points,
                // 轨迹的动画时长
                animationDuration: 5000,
                // 相机是否跟随动画移动
                isMapMoving: true,
                // 轨迹的颜色
                color: 0xAAFFAA00,
                // 轨迹的宽度
                width: 20,
                // 轨迹的动画回调(回调轨迹点的index)
                animationCallback: (pointIndex) => {
                  // 换成骑行
                  if (pointIndex === 10) {
                    markerBoy1.setVisible(false);
                    markerBoy2.setVisible(true);
                  }
                }
              }
              let markers: Array<map.Marker> = new Array();
              markers.push(markerBoy1, markerBoy2);
              // 新增轨迹点动画
              let traceOverlay = await this.mapController.addTraceOverlay(tranceOptions, markers);
            }
          }
        }
      
        build() {
          Stack() {
            Column() {
              MapComponent({
                mapOptions: this.mapOptions,
                mapCallback: this.callback,
              }).width('100%').height('100%');
            }.width('100%')
          }.height('100%')
        }
      }

      5.12 设置地图元素压盖顺序

      5.12.1 概述

      设置地图和各种覆盖物元素的层级压盖关系。

      设置地图元素的显示顺序,按照从低到高排列,即后面的覆盖物会压盖前面的覆盖物。

      表1 地图元素类型压盖顺序

      枚举

      枚举值

      枚举含义

      OVERLAY

      1

      覆盖物,包括MapCircle、MapPolygon、MapPolyline、MapArc、ImageOverlay、TraceOverlay。

      POI

      2

      底图Poi。

      CUSTOM_POI

      3

      支持碰撞的覆盖物,包括PointAnnotation、Bubble。

      MARKER

      4

      包括Marker、ClusterOverlay。

      5.12.2 接口说明

      设置层级压盖关系功能主要由MapElementType、setDisplayOrder提供,更多接口及使用方法请参见接口文档。

      接口名

      描述

      mapCommon.MapElementType

      地图元素类型。

      setDisplayOrder(types: Array<mapCommon.MapElementType>): void

      设置地图元素的显示顺序。

      5.12.3 开发步骤

              1. 导入相关模块。

      import { mapCommon, map, MapComponent } from '@kit.MapKit';
      import { AsyncCallback } from '@kit.BasicServicesKit';

                2. 设置地图元素层级压盖关系。

        @Entry
        @Component
        struct MarkerDemo {
          private mapOptions?: mapCommon.MapOptions;
          private mapController?: map.MapComponentController;
          private callback?: AsyncCallback<map.MapComponentController>;
          private mapEventManager?: map.MapEventManager;
          private marker?: map.Marker;
          private bubble?: map.Bubble;
        
          aboutToAppear(): void {
            // 地图初始化参数
            this.mapOptions = {
              position: {
                target: {
                  latitude: 31.984410259206815,
                  longitude: 118.26625379397866
                },
                zoom: 10
              }
            };
            this.callback = async (err, mapController) => {
              if (!err) {
                this.mapController = mapController;
                this.mapEventManager = this.mapController.getEventManager();
                // Marker初始化参数
                let markerOptions: mapCommon.MarkerOptions = {
                  position: {
                    latitude: 31.984410259206815,
                    longitude: 118.26625379397866
                  },
                  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);
                let bubbleOptions: mapCommon.BubbleParams = {
                  // 气泡位置
                  positions: [[{ latitude: 32.384410259206815, longitude: 118.26625379397866 }]],
                  // 设置图标,必须提供4个方向的图标,图标存放在resources/rawfile
                  icons: [
                    'speed_limit_10.png',
                    'speed_limit_20.png',
                    'speed_limit_30.png',
                    'speed_limit_40.png'
                  ],
                  // 定义气泡的显示属性,为true时,在被碰撞后仍能显示
                  forceVisible: true,
                  // 定义气泡碰撞优先级,数值越大,优先级越低
                  priority: 3,
                  // 定义气泡展示的最小层级
                  minZoom: 2,
                  // 定义气泡展示的最大层级
                  maxZoom: 20,
                  // 定义气泡是否可见
                  visible: true,
                  // 定义气泡叠加层级属性
                  zIndex: 1
                }
                // 添加气泡
                this.bubble = await this.mapController.addBubble(bubbleOptions);
                let imageOverlayParams: mapCommon.ImageOverlayParams = {
                  // 覆盖物范围
                  bounds: {
                    southwest: { latitude: 32, longitude: 118 },
                    northeast: { latitude: 32.4, longitude: 118.4 }
                  },
                  // 覆盖物图片
                  image: 'icon/icon.png',
                  transparency: 0.3,
                  zIndex: 101,
                  anchorU: 0.5,
                  anchorV: 0.5,
                  clickable: true,
                  visible: true,
                  bearing: 0
                };
                // 添加覆盖物
                await this.mapController?.addImageOverlay(imageOverlayParams);
                // 设置压盖顺序,最底层的是覆盖物,后面依次是POI、支持碰撞的覆盖物和Marker,Marker在最表面一层
                let mapElementTypeArr: Array<mapCommon.MapElementType> = [
                  mapCommon.MapElementType.OVERLAY,
                  mapCommon.MapElementType.POI,
                  mapCommon.MapElementType.CUSTOM_POI,
                  mapCommon.MapElementType.MARKER];
                this.mapController.setDisplayOrder(mapElementTypeArr);
              }
            };
          }
        
          build() {
            Stack() {
              Column() {
                MapComponent({ mapOptions: this.mapOptions, mapCallback: this.callback });
              }.width('100%')
            }.height('100%')
          }
        }

        6 位置搜索

        6.1 Poi搜索

        6.1.1 场景介绍

        提供多种查询Poi信息的能力:

        • 关键字搜索:通过用户输入的关键字,返回地点列表。
        • 周边搜索:基于用户设备位置进行地点查找。
        • 自动补全:根据输入的关键字返回预测的输入关键字和地点查询建议。
        • 地点详情:查询某个地点更详细的信息。

        6.1.2 接口说明

        以下是Poi搜索相关接口,主要由site命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        searchByText(searchByTextParams: SearchByTextParams): Promise<SearchByTextResult>

        关键字搜索。

        searchByText(context: common.Context, searchByTextParams: SearchByTextParams): Promise<SearchByTextResult>

        关键字搜索。支持上传Context上下文。

        nearbySearch(nearbySearchParams: NearbySearchParams): Promise<NearbySearchResult>

        周边搜索。

        nearbySearch(context: common.Context, nearbySearchParams: NearbySearchParams): Promise<NearbySearchResult>

        周边搜索。支持上传Context上下文。

        queryAutoComplete(queryAutoCompleteParams: QueryAutoCompleteParams): Promise<QueryAutoCompleteResult>

        自动补全。

        queryAutoComplete(context: common.Context, queryAutoCompleteParams: QueryAutoCompleteParams): Promise<QueryAutoCompleteResult>

        自动补全。支持上传Context上下文。

        searchById(searchByIdParams: SearchByIdParams): Promise<SearchByIdResult>

        地点详情。

        searchById(context: common.Context, searchByIdParams: SearchByIdParams): Promise<SearchByIdResult>

        地点详情。支持上传Context上下文。

        SearchByTextParams

        关键字搜索的参数。

        NearbySearchParams

        周边搜索的参数。

        QueryAutoCompleteParams

        自动补全的参数。

        SearchByIdParams

        地点详情的参数。

        SearchByTextResult

        关键字搜索的结果。

        NearbySearchResult

        周边搜索的结果。

        QueryAutoCompleteResult

        自动补全的结果。

        SearchByIdResult

        地点详情的结果。

        6.1.3 开发步骤

                1. 导入相关模块。

        import { site } from '@kit.MapKit';
        1、关键字搜索

        通过指定的关键字和可选的地理范围,查询诸如旅游景点、企业和学校之类的地点。

        let params: site.SearchByTextParams = {
          // 指定关键字
          query: "Piazzale Dante, 41, 55049 Viareggio, Tuscany, Italy",
          // 经纬度坐标
          location: {
            latitude: 31.984,
            longitude: 118.76625
          },
          // 指定地理位置的范围半径
          radius: 10000,
          language: "en"
        };
        // 返回关键字搜索结果
        const result = await site.searchByText(params);
        console.info("Succeeded in searching by text.");
        2、周边搜索

        通过用户传入自己的位置,可以返回周边地点列表。您可以通过提供关键字或指定要搜索的地点的类型来优化搜索结果。

        let params: site.NearbySearchParams = {
          // 指定关键字
          query: "stazione di pomezia",
          // 经纬度坐标
          location: {
            latitude: 31.984410259206815,
            longitude: 118.76625379397866
          },
          // 指定地理位置的范围半径
          radius: 5000,
          // 指定需要展示的poi类别
          poiTypes: ["NATIONAL_RAILWAY_STATION"],
          language: "en",
          pageIndex: 1,
          pageSize: 1
        };
        // 返回周边搜索结果
        const result = await site.nearbySearch(params);
        console.info("Succeeded in searching nearby.");
        3、自动补全

        根据输入的关键字,将最有可能的搜索词呈现给用户,以减少用户输入信息,提升用户体验。如:输入“北京”,提示“北京市”、“北京站”、“北京西站”等。

        let params: site.QueryAutoCompleteParams = {
          // 指定关键字
          query: "hotel",
          // 经纬度坐标
          location: {
            latitude: 31.984410259206815,
            longitude: 118.76625379397866
          },
          language: "en",
          // 返回子节点
          isChildren: true
        };
        // 返回自动补全结果
        const result = await site.queryAutoComplete(params);
        console.info("Succeeded in querying.");
        4、地点详情

        根据地点的唯一主键地点ID(siteId)获取地点详情。地点详细信息请求返回有关指定地点的更全面的信息,如地点名称、地址详细信息、经纬度等。siteId可通过其他接口(关键字搜索、周边搜索、地点详情、自动补全、正地理编码)的返回结果中获取。

        let params: site.SearchByIdParams = {
          // 指定主键地点ID
          siteId: "144129739873977856",
          language: "en",
          // 返回子节点
          isChildren: true
        };
        // 返回地点详情结果
        const result = await site.searchById(params);
        console.info("Succeeded in searching.");

        6.2 地理编码

        6.2.1 场景介绍

        提供正地理编码、逆地理编码的能力:

        • 正地理编码:根据地址获取地点的经纬度。
        • 逆地理编码:获取经纬度对应的地点信息。

        6.2.2 接口说明

        以下是地理编码相关接口,主要由site命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        geocode(geocodeParams: GeocodeParams): Promise<GeocodeResult>

        正地理编码。

        geocode(context: common.Context, geocodeParams: GeocodeParams): Promise<GeocodeResult>

        正地理编码。支持上传Context上下文。

        reverseGeocode(reverseGeocodeParams: ReverseGeocodeParams): Promise<ReverseGeocodeResult>

        逆地理编码。

        reverseGeocode(context: common.Context, reverseGeocodeParams: ReverseGeocodeParams): Promise<ReverseGeocodeResult>

        逆地理编码。支持上传Context上下文。

        GeocodeParams

        正地理编码的参数。

        GeocodeResult

        正地理编码的结果。

        ReverseGeocodeParams

        逆地理编码的参数。

        ReverseGeocodeResult

        逆地理编码的结果。

        6.2.3 开发步骤

                1. 导入相关模块。

        import { site } from '@kit.MapKit';
        1、正地理编码

        说明

        根据地址获取地点的空间坐标,如经纬度,最多返回10条记录。

        let params: site.GeocodeParams = {
          // 地址信息
          "query": "Piazzale Dante, 41, 55049 Viareggio",
          "language": "en"
        };
        const result = await site.geocode(params);
        console.info("Succeeded in geocoding.");
        2、逆地理编码

        说明

        根据经纬度获取附近200m内地点的详细地址,最多返回11条记录。

        let params: site.ReverseGeocodeParams = {
          // 位置经纬度
          location: {
            latitude: 31.984410259206815,
            longitude: 118.76625379397866
          },
          language: "en",
          radius: 200
        };
        const result = await site.reverseGeocode(params);
        console.info("Succeeded in reversing.");

        7 路径规划

        7.1 出行路线规划

        7.1.1 场景介绍

        提供两点之间驾车、步行、骑行的路径规划能力。其中驾车路径规划支持添加途径点。

        7.1.2 接口说明

        以下是路径规划功能相关接口,主要由navi命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        getDrivingRoutes(params: DrivingRouteParams): Promise<RouteResult>

        驾车路径规划。

        getDrivingRoutes(context: common.Context, params: DrivingRouteParams): Promise<RouteResult>

        驾车路径规划。支持传入Context上下文。

        getWalkingRoutes(params: RouteParams): Promise<RouteResult>

        步行路径规划。

        getWalkingRoutes(context: common.Context, params: RouteParams): Promise<RouteResult>

        步行路径规划。支持传入Context上下文。

        getCyclingRoutes(params: RouteParams): Promise<RouteResult>

        骑行路径规划。

        getCyclingRoutes(context: common.Context, params: RouteParams): Promise<RouteResult>

        骑行路径规划。支持传入Context上下文。

        DrivingRouteParams

        驾车路径规划的参数。

        RouteParams

        步行、骑行路径规划的参数。

        RouteResult

        路径规划的结果。

        7.1.3 开发步骤

                1. 导入相关模块。

        import { navi } from '@kit.MapKit';
        1、驾车路径规划

        根据起终点坐标检索符合条件的驾车路径规划方案。支持以下功能:

        • 支持一次请求返回多条路线,最多支持3条路线。
        • 最多支持5个途经点。
        • 支持未来出行规划。
        • 支持根据实时路况进行合理路线规划。
        • 支持多种路线偏好选择,如时间最短、避免经过收费的公路、避开高速公路、距离优先等。
        async testDrivingRoutes(){
          let params: navi.DrivingRouteParams = {
            // 起点的经纬度
            origins: [{
              "latitude": 31.982129213545843,
              "longitude": 120.27745557768591
            }],
            // 终点的经纬度
            destination: {
              "latitude": 31.982129213545843,
              "longitude": 120.27745557768591
            },
            // 路径的途经点
            waypoints: [{ "latitude": 31.967236140819114, "longitude": 120.27142088866847 },
              { "latitude": 31.972868002238872, "longitude": 120.2943211817165 },
              { "latitude": 31.98469327973332, "longitude": 120.29101107384068 }],
            language: "zh_CN"
          };
          const result = await navi.getDrivingRoutes(params);
          console.info("Succeeded in getting driving routes.");
        }
        2、步行路径规划

        根据起终点坐标检索符合条件的步行路径规划方案。支持以下功能:

        • 支持150km以内的步行路径规划能力。
        • 融入出行策略(时间最短、避免轮渡)。
        async testWalkingRoutes(){
          let params: navi.RouteParams = {
            // 起点的经纬度
            origins: [{ "latitude": 39.992281, "longitude": 116.31088 }, { "latitude": 39.996, "longitude": 116.311 }],
            // 终点的经纬度
            destination: { "latitude": 39.94, "longitude": 116.311 },
            language: "zh_CN"
          };
          const result = await navi.getWalkingRoutes(params);
          console.info("Succeeded in getting walking routes.");
        }
         3、骑行路径规划

        根据起终点坐标检索符合条件的骑行路径规划方案。支持以下功能:

        • 支持500km以内的骑行路径规划能力。
        • 融入出行策略(时间最短、避免轮渡)。
        async testCyclingRoutes() {
          let params: navi.RouteParams = {
            // 起点的经纬度
            origins: [{ latitude: 31.9844102, longitude: 118.7662537 }],
            // 终点的经纬度
            destination: { latitude: 31.9874102, longitude: 118.7362537 },
            language: "zh_CN"
          };
          const result = await navi.getCyclingRoutes(params);
          console.info("Succeeded in getting cycling routes.");
        }

        7.2 批量算路

        7.2.1 场景介绍

        多个起点到多个终点的批量算路功能,在驾车、步行、骑行模式下,快速批量计算多个起点分别到多个终点的路线距离和耗时。

        7.2.2 接口说明

        以下是路径规划功能相关接口,主要由navi命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        getDrivingMatrix(params: DrivingMatrixParams): Promise<MatrixResult>

        驾车批量算路。

        getDrivingMatrix(context: common.Context, params: DrivingMatrixParams): Promise<MatrixResult>

        驾车批量算路。支持传入Context上下文。

        getWalkingMatrix(params: MatrixParams): Promise<MatrixResult>

        步行批量算路。

        getWalkingMatrix(context: common.Context, params: MatrixParams): Promise<MatrixResult>

        步行批量算路。支持传入Context上下文。

        getCyclingMatrix(params: MatrixParams): Promise<MatrixResult>

        骑行批量算路。

        getCyclingMatrix(context: common.Context, params: MatrixParams): Promise<MatrixResult>

        骑行批量算路。支持传入Context上下文。

        DrivingMatrixParams

        驾车批量算路的参数。

        MatrixParams

        步行、骑行批量算路的参数。

        MatrixResult

        批量算路的结果。

        7.2.3 开发步骤

                1. 导入相关模块。

        import { navi } from '@kit.MapKit';
        1、驾车批量算路

        根据多组起终点坐标批量检索符合条件的驾车路径规划方案。支持以下功能:

        • 支持未来出行规划。
        • 支持根据实时路况进行合理路线规划。
        • 支持多种路线偏好选择,如时间最短、避免经过收费的公路、避开高速公路、距离优先等。

        说明

        限制:起点数乘以终点数需小于100。

        async testDrivingMatrix() {
          let params: navi.DrivingMatrixParams = {
            // 起点的经纬度
            "origins": [
              { "latitude": 31.9844, "longitude": 118.766253 },
              { "latitude": 31.9644, "longitude": 118.746253 }
            ],
            // 终点的经纬度
            "destinations": [
              { "latitude": 31.9344, "longitude": 118.706253 }
            ],
            // 时间预估模型
            "trafficMode": 2,
            "language": "zh_CN"
          };
          const result = await navi.getDrivingMatrix(params);
          console.info("Succeeded in getting driving matrix.");
        }
        2、步行批量算路

        根据多组起终点坐标批量检索符合条件的步行路径规划方案。支持以下功能:

        • 支持150km以内的步行路径规划能力。
        • 融入出行策略(时间最短、避免轮渡)。

        说明

        限制:起点数乘以终点数需小于100。

        async testWalkingMatrix() {
          let params: navi.MatrixParams = {
            // 起点的经纬度
            "origins": [
              { "latitude": 31.9844, "longitude": 118.766253 },
              { "latitude": 31.9644, "longitude": 118.746253 }
            ],
            // 终点的经纬度
            "destinations": [{ "latitude": 31.9344, "longitude": 118.706253 }],
            "language": "zh_CN"
          };
          const result = await navi.getWalkingMatrix(params);
          console.info("Succeeded in getting walking matrix.");
        }
        3、骑行批量算路

        根据多组起终点坐标批量检索符合条件的骑行路径规划方案。支持以下功能:

        • 支持500km以内的骑行路径规划能力。
        • 融入出行策略(时间最短、避免轮渡)。

        说明

        限制:起点数乘以终点数需小于100。

        async testCyclingMatrix() {
          let params: navi.MatrixParams = {
            // 起点的经纬度
            "origins": [
              { "latitude": 31.9844, "longitude": 118.766253 },
              { "latitude": 31.9644, "longitude": 118.746253 }
            ],
            // 终点的经纬度
            "destinations": [{ "latitude": 31.9344, "longitude": 118.706253 }],
            "language": "zh_CN"
          };
          const result = await navi.getCyclingMatrix(params);
          console.info("Succeeded in getting cycling matrix.");
        }

        7.3 轨迹绑路

        7.3.1 场景介绍

        根据给定的坐标点捕捉道路,将用户的轨迹纠正到道路上,从而返回用户实际驾车经过的道路坐标。

        7.3.2 接口说明

        以下是路径规划功能相关接口,主要由navi命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        SnapToRoadsParams

        轨迹绑路的参数。

        snapToRoads(params: SnapToRoadsParams): Promise<SnapToRoadsResult>

        轨迹绑路。

        snapToRoads(context: common.Context, params: SnapToRoadsParams): Promise<SnapToRoadsResult>

        轨迹绑路。支持传入Context上下文。

        SnapToRoadsResult

        轨迹绑路的结果。

        7.3.3 开发步骤

                1. 导入相关模块。

        import { navi } from '@kit.MapKit';
        1、轨迹绑路

        根据给定的坐标点捕捉道路,将用户的轨迹纠正到道路上,从而返回用户实际驾车经过的道路坐标。

        async testSnapToRoads() {
          let params: navi.SnapToRoadsParams = {
            // 道路贴合点集合,不能超过100个,且相邻两个点距离需小于等于500米
            points: [{
              latitude: 31.984410259206815,
              longitude: 118.76625379397866
            }]
          };
          const result = await navi.snapToRoads(params);
          console.info("Succeeded in snapping to roads.");
        }

        8 静态图 

        8.1 场景介绍

        静态图功能会返回一张地图图片,将地图以图片形式嵌入自己的应用/元服务中。在使用时,可以指定请求的地图位置、图片大小。

        8.2 接口说明

        以下是地图静态图相关接口,获取静态图功能主要由staticMap命名空间下的方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        StaticMapOptions

        用于描述静态图属性。

        getMapImage(options: StaticMapOptions): Promise<image.PixelMap>

        根据提供的参数创建静态图。

        getMapImage(context: common.Context, options: StaticMapOptions): Promise<image.PixelMap>

        根据提供的参数创建静态图。支持上传Context上下文。

        8.3 开发步骤

                1. 导入相关模块。

        import { staticMap } from '@kit.MapKit';
        

                2. 创建静态图初始化参数,调用getMapImage方法获取静态图,效果如下图。

        @Entry
        @Component
        struct StaticMapDemo {
          @State image?: PixelMap = undefined;
        
          build() {
            Column() {
              this.buildDemoUI();
            }.width('100%')
            .margin({ bottom: 48 })
            .backgroundColor(0xf2f2f2)
            .height('100%')
          }
        
          @Builder
          buildDemoUI() {
            // 展示获取的静态图
            Image(this.image)
              .width('100%')
              .fitOriginalSize(false)
              .border({ width: 1 })
              .borderStyle(BorderStyle.Dashed)
              .objectFit(ImageFit.Contain)
              .height("90%")
        
            Row() {
              Button("getStaticMap")
                .fontSize(12)
                .onClick(async () => {
                  // 设置静态图标记参数
                  let markers: Array<staticMap.StaticMapMarker> = [{
                    location: {
                      latitude: 50,
                      longitude: 126.3
                    },
                    font: 'statics',
                    defaultIconSize: staticMap.IconSize.TINY
                  }];
        
                  // 设置静态图绘制路径参数
                  let path: staticMap.StaticMapPath = {
                    locations: [
                      {
                        latitude: 50,
                        longitude: 126
                      },
                      {
                        latitude: 50.3,
                        longitude: 126
                      },
                      {
                        latitude: 50.3,
                        longitude: 126.3
                      },
                      {
                        latitude: 49.7,
                        longitude: 126
                      },
                      {
                        latitude: 50,
                        longitude: 126
                      }
                    ],
                    width: 3
                  };
        
                  // 拼装静态图参数
                  let option: staticMap.StaticMapOptions = {
                    location: {
                      latitude: 50,
                      longitude: 126
                    },
                    zoom: 10,
                    imageWidth: 1024,
                    imageHeight: 1024,
                    scale: 1,
                    markers: markers,
                    path: path
                  };
        
                  // 获取静态图
                  await staticMap.getMapImage(option).then((value) => {
                    this.image = value;
                    console.info("Succeeded in getting image.");
                  });
                })
            }.margin({ top: 12 })
          }
        }
        

        图1 调用getMapImage方法获取静态图
         

        9 地图Picker

        9.1 地点详情展示

        9.1.1 场景介绍

        如何集成地点详情展示控件,无需自己开发地图页面,可快速实现查看地点详情展示功能。

        9.1.2 接口说明

        地点详情展示控件功能主要由sceneMap命名空间下的queryLocation方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        LocationQueryOptions

        查询地点详情的参数。

        queryLocation(context: common.UIAbilityContext, options: LocationQueryOptions): Promise<void>

        查询地点详情。

        9.1.3 开发步骤

                1. 导入相关模块。

        import { sceneMap } from '@kit.MapKit';
        import { BusinessError } from '@kit.BasicServicesKit';
        import { common } from '@kit.AbilityKit';
        

                2. 创建查询地点详情参数,调用queryLocation方法拉起地点详情页。

        let queryLocationOptions: sceneMap.LocationQueryOptions = { siteId: "922207154068557824" };
        // 拉起地点详情页
        sceneMap.queryLocation(getContext(this) as common.UIAbilityContext, queryLocationOptions).then(() => {
          console.info("QueryLocation", "Succeeded in querying location.");
        }).catch((err: BusinessError) => {
          console.error("QueryLocation", `Failed to query Location, code: ${err.code}, message: ${err.message}`);
        });
        

        9.2 地点选取

        9.2.1 场景介绍

        如何集成地点选取控件,无需自己开发地图页面,可快速实现地点选取的能力。

        9.2.2 接口说明

        地点选取控件功能主要由sceneMap命名空间下的chooseLocation方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        LocationChoosingOptions

        地点选取的参数。

        chooseLocation(context: common.UIAbilityContext, options: LocationChoosingOptions): Promise<LocationChoosingResult>

        地点选取。

        LocationChoosingResult

        地点选取的返回结果。

        9.2.3 开发步骤

                1. 导入相关模块。

        import { sceneMap } from '@kit.MapKit';
        import { BusinessError } from '@kit.BasicServicesKit';
        import { common } from '@kit.AbilityKit';
        

                2. 创建地点选取参数,调用chooseLocation方法拉起地点选取页。

        let locationChoosingOptions: sceneMap.LocationChoosingOptions = {
          // 地图中心点坐标
          location: { latitude: 39.92194051376904, longitude: 116.3971836796932 },
          language: 'en',
          // 展示搜索控件
          searchEnabled: true,
          // 展示附近Poi
          showNearbyPoi: true
        };
        // 拉起地点选取页
        sceneMap.chooseLocation(getContext(this) as common.UIAbilityContext, locationChoosingOptions).then((data) => {
          console.info("ChooseLocation", "Succeeded in choosing location.");
        }).catch((err: BusinessError) => {
          console.error("ChooseLocation", `Failed to choose location, code: ${err.code}, message: ${err.message}`);
        });
        

        9.3 区划选择

        9.3.1 场景介绍

        集成区划选择控件。

        区划选择控件可加载全球或指定国家的区划信息,支持以树状结构化选择。支持功能:

        • 支持查看选中区划的下级区划。
        • 支持推荐热门区划。

        图1 选择国家

        图2 选择省市

        9.3.2 接口说明

        区划选择控件功能主要由sceneMap命名空间下的selectDistrict方法提供,更多接口及使用方法请参见接口文档。

        接口名

        描述

        DistrictSelectOptions

        行政区划选择页面初始选项。

        selectDistrict(context: common.Context, options: DistrictSelectOptions): Promise<DistrictSelectResult>

        调出行政区划选择页面。

        DistrictSelectResult

        行政区划选择结果。

        9.3.3 开发步骤

                1. 导入相关模块。

        import { sceneMap } from '@kit.MapKit';
        import { BusinessError } from '@kit.BasicServicesKit';
        

                 2. 创建行政区划选择请求参数,调用selectDistrict方法拉起行政区划选择页。

        let districtSelectOptions: sceneMap.DistrictSelectOptions= {
          countryCode: "CN"
        };
        // 拉起行政区划选择页
        sceneMap.selectDistrict(getContext(this), districtSelectOptions).then((data) => {
          console.info("SelectDistrict", "Succeeded in selecting district.");
        }).catch((err: BusinessError) => {
          console.error("SelectDistrict", `Failed to select district, code: ${err.code}, message: ${err.message}`);
        });
        

        10. 通过Petal 地图应用实现导航等能力

        10.1 通过AppLinking拉起Petal Maps鸿蒙应用APP

        Petal 地图提供了通过AppLinking拉起应用的能力。 当前可以通过AppLinking拉起地图应用到首页、路径规划、导航、地点详情、地点搜索页面。

        该功能支持的Petal 地图应用版本大于等于1.7.0.300。

        接口名称

        接口调用方向

        接口描述

        拉起Petal 地图 APP

        Map Kit或三方应用 -> Petal 地图 APP

        HarmonyOS系统openLink接口。

        10.2 拉起方实现跳转

        通过openLink接口拉起。将appLinkingOnly参数设为true,若有匹配的应用,则直接打开目标应用。若无App Linking匹配的应用, 目前openLink接口会抛异常给开发者进行处理。鸿蒙将会支持,在没有安装应用时候,牵引用户到应用市场进行下载。

        10.3 Petal 地图使用的坐标类型

        在国内站点,中国大陆、中国香港和中国澳门使用GCJ02坐标系,中国台湾使用WGS84坐标系。

        在海外站点,统一使用WGS84坐标系。坐标系转换参考:地图坐标系说明及转换。

        10.4 拉起Petal 地图首页

        import { common } from '@kit.AbilityKit';
        const uri = 'https://www.petalmaps.com';
         let context = getContext(this) as common.UIAbilityContext;
        context.openLink(uri, {
          appLinkingOnly: true
        })
        
        • Uri定义

        参数名

        类型

        必填

        说明

        uri

        string

        拉起页面地址,https://www.petalmaps.com。

        • Parameters配置参数定义

        参数名

        类型

        必填

        说明

        utm_source

        string

        接入方业务名或包名,Link请求来源。

        • 效果截图示例 

          图1 手机

          图2 平板

        10.5 拉起Petal 地图查看位置详情

        通过传入位置的经纬度或者位置的详情ID,拉起Petal地图查看位置详情。

        import { common } from '@kit.AbilityKit';
        const uri = 'https://www.petalmaps.com/place/?z=16&marker=48.2944863308775,4.07333135604859&placeId=653905656638747008';  
        let context = getContext(this) as common.UIAbilityContext;
        context.openLink(uri, {
          appLinkingOnly: true
        })
        
        • Uri定义

        参数名

        类型

        必填

        说明

        uri

        string

        拉起页面地址,https://www.petalmaps.com/place。

        • Parameters配置参数定义

        参数名

        类型

        必填

        说明

        utm_source

        string

        接入方业务名或包名,Link请求来源。

        marker

        string

        位置经纬度。

        placeId

        string

        位置ID,如果有,优先使用。如果没有填写placeId,则调用逆地理接口,展示位置及其对应的经纬度。

        z

        string

        z取层级范围3~20的整数,不符合或不填则按照默认层级展示。

        coordinateType

        string

        传入的经纬度的坐标系类型。0-WGS84,1-GCJ02,默认GCJ02。

        • 效果截图示例 

          图3 手机

          图4 平板

        拉起Petal 地图查看路径规划

        通过传入起始点经纬度规划路线。

        import { common } from '@kit.AbilityKit';
        const uri = 'https://www.petalmaps.com/routes/?saddr=25.102916,55.165363&daddr=25.164610000000,55.228869000000&type=walk&utm_source=fb';
        let context = getContext(this) as common.UIAbilityContext;
        context.openLink(uri, {
           appLinkingOnly: true
        });
        
        • Uri定义

        参数名

        类型

        必填

        说明

        uri

        string

        拉起页面地址,https://www.petalmaps.com/routes。

        • Parameters配置参数定义

        参数名

        类型

        必填

        说明

        utm_source

        string

        Link请求来源,接入方业务名或包名。

        saddr

        string

        起点经纬度(纬度在前,经度在后),默认取当前位置。支持经纬度+名称, 名称括号为英文格式,中间可以有空格。例:48.883653,2.311279(中 软国际),名称括号为英文格式,中间可以有空格,拉起地图后起终点显示中软国际。支持家或公司, 家对应参数值为home公司的参数值为company,没有设置家或公司则拉起设置页。

        daddr

        string

        终点经纬度(纬度在前,经度在后), 支持经纬度+名称, 名称括号为英文格式,中间可以有空格。例:48.883653,2.311279(中 软国际),名称括号为英文格式,中间可以有空格,拉起地图后起终点显示中软国际。支持家或公司, 家对应参数值为home公司的参数值为company,没有设置家或公司则拉起设置页。

        type

        string

        交通出行工具。drive(驾车)、bus(公交)、walk(步行)、bicycle(骑行), 不填或者错误格式会默认是驾车。

        coordinateType

        string

        传入的经纬度的坐标系类型。0-WGS84,1-GCJ02,默认GCJ02。

        • 效果截图示例 

          图5 手机

          图6 平板

        拉起Petal 地图发起导航

        通过传入终点经纬度直接发起导航。

        import { common } from '@kit.AbilityKit';
        const uri = 'https://www.petalmaps.com/navigation/?saddr=31.97655,118.568523(测试1)&daddr=31.8888,118.6584722(测试2)&type=drive&utm_source=ft';let context = getContext(this) as common.UIAbilityContext
        context.openLink(uri, {
           appLinkingOnly: true
        })
        
        • Uri定义

        参数名

        类型

        必填

        说明

        uri

        string

        拉起页面地址, https://www.petalmaps.com/navigation。

        • Parameters配置参数定义

        参数名

        类型

        必填

        说明

        utm_source

        string

        Link请求来源,接入方业务名或包名。

        saddr

        string

        起点经纬度(纬度在前,经度在后),默认取当前位置。支持经纬度+名称。支持家或公司。

        daddr

        string

        终点经纬度(纬度在前,经度在后),支持经纬度+名称。支持家或公司。

        type

        string

        交通出行工具。drive(驾车)、bus(公交)、walk(步行)、bicycle(骑行), 不填或者错误格式会默认是驾车。如果填bus拉起地图后会停留在路线规划页面,不会发起导航。

        coordinateType

        string

        传入的经纬度的坐标系类型。0-WGS84,1-GCJ02,默认GCJ02 。

        • 效果截图示例 

          图7 手机

          图8 平板

        拉起Petal 地图进行位置搜索

        通过传入搜索目标名称,搜索附近地点。

        import { common } from '@kit.AbilityKit';
        const uri = 'www.petalmaps.com/search/?q=coffee&utm_source=fb';
        let context = getContext(this) as common.UIAbilityContext;
        context.openLink(uri, {
          appLinkingOnly: true
        })
        
        • Uri定义

        参数名

        类型

        必填

        说明

        uri

        string

        拉起页面地址,https://www.petalmaps.com/search。

        • Parameters配置参数定义

        参数名

        类型

        必填

        说明

        utm_source

        string

        Link请求来源,接入方业务名或包名。

        q

        string

        位置名称。

        • 效果截图示例 

          图9 手机

          图10 平板

              本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2303598.html

              如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

              相关文章

              EasyExcel 自定义头信息导出

              需求&#xff1a;需要在导出 excel时&#xff0c;合并单元格自定义头信息(动态生成)&#xff0c;然后才是字段列表头即导出数据。 EasyExcel - 使用table去写入&#xff1a;https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write#%E4%BD%BF%E7%94%A8table%E…

              DeepSeek 提示词:定义、作用、分类与设计原则

              &#x1f9d1; 博主简介&#xff1a;CSDN博客专家&#xff0c;历代文学网&#xff08;PC端可以访问&#xff1a;https://literature.sinhy.com/#/?__c1000&#xff0c;移动端可微信小程序搜索“历代文学”&#xff09;总架构师&#xff0c;15年工作经验&#xff0c;精通Java编…

              ubuntu环境编译ffmepg支持nvidia显卡加速

              文章目录 1. 安装NVIDIA驱动2. 安装CUDA&NV-CODEC2.1 安装CUDA2.2 安装NV-CODEC 3. 编译ffmpeg3.1 安装依赖3.2 下载源码安装依赖3.3 验证 4. 使用 1. 安装NVIDIA驱动 安装依赖包 sudo apt install -y ubuntu-drivers-common编辑 /etc/modprobe.d/blacklist-nouveau.conf 文…

              边缘安全加速(Edge Security Acceleration)

              边缘安全加速&#xff08;Edge Security Acceleration&#xff0c;简称ESA&#xff09;是一种通过将安全功能与网络边缘紧密结合来提升安全性和加速网络流量的技术。ESA的目标是将安全措施部署到接近用户或设备的地方&#xff0c;通常是在网络的边缘&#xff0c;而不是将所有流…

              SpringCould+vue3项目的后台用户管理的CURD【Taurus教育平台】

              文章目录 一.SpringCouldvue3项目的后台用户管理的CURD【Taurus教育平台】 1.1 背景 二.用户列表&#xff08;分页查询&#xff09; 2.1 前端Vue3 &#xff08;Vue3-Element-Admin&#xff09;2.2 后端SpringCould 处理 三. 用户信息删除 3.1 前端Vue3 &#xff08;Vue3-Eleme…

              ROS-相机话题-获取图像-颜色目标识别与定位-目标跟随-人脸检测

              文章目录 相机话题获取图像颜色目标识别与定位目标跟随人脸检测 相机话题 启动仿真 roslaunch wpr_simulation wpb_stage_robocup.launch rostopic hz /kinect2/qhd/image_color_rect/camera/image_raw&#xff1a;原始的、未经处理的图像数据。 /camera/image_rect&#xff…

              调用click.getchar()时Windows PyCharm无法模拟键盘输入

              文章目录 问题描述解决方案参考文献 问题描述 调用 click.getchar() 时&#xff0c;Windows PyCharm 无法模拟键盘输入 解决方案 Run → Edit Configurations… → Modify options → Emulate terminal in output console 参考文献 Terminal emulator | PyCharm Documentati…

              易基因: ChIP-seq+DRIP-seq揭示AMPK通过调控H3K4me3沉积和R-loop形成以维持基因组稳定性和生殖细胞完整性|NAR

              原文&#xff1a;ChIP-seqDRIP-seq揭示AMPK通过调控H3K4me3沉积和R-loop形成以维持基因组稳定性和生殖细胞完整性&#xff5c;NAR 大家好&#xff0c;这里是专注表观组学十余年&#xff0c;领跑多组学科研服务的易基因。 在饥饿等能量胁迫条件下&#xff0c;生物体会通过调整…

              数据中心储能蓄电池状态监测管理系统 组成架构介绍

              安科瑞刘鸿鹏 摘要 随着数据中心对供电可靠性要求的提高&#xff0c;蓄电池储能系统成为关键的后备电源。本文探讨了蓄电池监测系统在数据中心储能系统中的重要性&#xff0c;分析了ABAT系列蓄电池在线监测系统的功能、技术特点及其应用优势。通过蓄电池监测系统的实施&#…

              01数据准备 抓取图片 通过爬虫方式获取bing的关键词搜索图片

              为了获取训练所需的图片,我们最常用的手段就是自己去写一个爬虫去获取相关图片。本文将重点围绕如何采用爬虫的方式获取训练所需的图片素材进行讲解,为了大家能够够直观的掌握相关技术,参考本文的相关过程和代码获取自己的数据图片素材,笔者将详细介绍实现过程。 1、确定图…

              【UCB CS 61B SP24】Lecture 5 - Lists 3: DLLists and Arrays学习笔记

              本文内容为构建双向循环链表、使用 Java 的泛型将其优化为通用类型的链表以及数组的基本语法介绍。 1. 双向链表 回顾上一节课写的代码&#xff0c;当执行 addLast() 与 getLast() 方法时需要遍历链表&#xff0c;效率不高&#xff0c;因此可以添加一个指向链表末尾的索引&am…

              Git 工作流程

              1、Git 工作流程 http://www.ruanyifeng.com/blog/2015/12/git-workflow.html git push -f origin HEAD^:master 删除服务器上最近的一次提交git push -f origin HEAD^:master 2、Git分支管理 动画形式演示分支效果&#xff1a; http://onlywei.github.io/explain-git-with-…

              DeepSeek接入Siri(已升级支持苹果手表)完整版硅基流动DeepSeek-R1部署

              DeepSeek接入Siri&#xff08;已升级支持苹果手表&#xff09;完整版硅基流动DeepSeek-R1部署 **DeepSeek** 是一款专注于深度学习和人工智能的工具或平台&#xff0c;通常与人工智能、机器学习、自动化分析等领域有关。它的主要功能可能包括&#xff1a;深度学习模型搜索&…

              个人博客5年回顾

              https://huangtao01.github.io/ 五年前&#xff0c;看程序羊的b站视频做的blog&#xff0c;受限于网络&#xff0c;只能单向学习&#xff0c;没有人指导与监督&#xff0c;从来没有想过&#xff0c;有没有什么问题&#xff1f; 一、为什么要做个人博客&#xff1f; 二、我是怎么…

              nacos编写瀚高数据库插件

              1、下载nacos源码 git clone gitgithub.com:alibaba/nacos.git 2、引入瀚高驱动 <dependency><groupId>com.highgo</groupId><artifactId>jdbc</artifactId><version>${highgo.version}</version></dependency> 3、DataSource…

              bboss v7.3.5来袭!新增异地灾备机制和Kerberos认证机制,助力企业数据安全

              ETL & 流批一体化框架 bboss v7.3.5 发布&#xff0c;多源输出插件增加为特定输出插件设置记录过滤功能&#xff1b;Elasticsearch 客户端新增异地双中心灾备机制&#xff0c;提升框架高可用性&#xff1b;Elasticsearch client 和 http 微服务框架增加对 Kerberos 认证支持…

              《Python实战进阶》专栏 No2: Flask 中间件与请求钩子的应用

              专栏简介 《Python实战进阶》专栏共68集&#xff0c;分为 模块1&#xff1a;Web开发与API设计&#xff08;共10集&#xff09;&#xff1b;模块2&#xff1a;数据处理与分析&#xff08;共10集&#xff09;&#xff1b;模块3&#xff1a;自动化与脚本开发&#xff08;共8集&am…

              Redis三剑客解决方案

              文章目录 缓存穿透缓存穿透的概念两种解决方案: 缓存雪崩缓存击穿 缓存穿透 缓存穿透的概念 每一次查询的 key 都不在 redis 中&#xff0c;数据库中也没有。 一般都是属于非法的请求&#xff0c;比如 id<0&#xff0c;比如可以在 API 入口做一些参数校验。 大量访问不存…

              Frp部署文档

              Frp部署文档 开源项目地址:https://github.com/fatedier/frp项目中文文档地址&#xff1a;https://github.com/fatedier/frp/blob/dev/README_zh.md官网文档地址: https://gofrp.org/zh-cn/docs/发布包地址&#xff1a;https://github.com/fatedier/frp/releases 要注意对应的…

              创建一个简单的spring boot+vue前后端分离项目

              一、环境准备 此次实验需要的环境&#xff1a; jdk、maven、nvm和node.js 开发工具&#xff1a;idea或者Spring Tool Suite 4&#xff0c;前端可使用HBuilder X&#xff0c;数据库Mysql 下面提供maven安装与配置步骤和nvm安装与配置步骤&#xff1a; 1、maven安装与配置 1…