鸿蒙Flutter实战:20. Flutter集成高德地图,同层渲染

本文以同层渲染为例,介绍如何集成高德地图

完整代码见 Flutter 鸿蒙版 Demo

概述

Dart 侧

核心代码如下,通过 OhosView 来承载原生视图

dart 复制代码
OhosView(
      viewType: 'com.shaohushuo.app/customView',
      onPlatformViewCreated: _onPlatformViewCreated,
      creationParams: const <String, dynamic>{'initParams': 'hello world'},
      creationParamsCodec: const StandardMessageCodec(),
    )

其中 viewType 为自定义的 ohosView 的名称,onPlatformViewCreated 为创建完成回调,creationParams 为创建时传入的参数,creationParamsCodec 为参数编码格式。

ArkTS 侧

这里面我们按照《如何使用PlatformView》中的示例操作,首先需要创建一个显示高德地图的视图,其核心代码如下:

完整文件 AmapWidgetFactory.ets

dart 复制代码
MapsInitializer.setApiKey("e4147e927a1f63a0acff45cecf9419b5");
MapViewManager.getInstance().registerMapViewCreatedCallback((mapview?: MapView, mapViewName?: string) => {
  if (!mapview) {
    return;
  }
  let mapView = mapview;
  mapView.onCreate();
  mapView.getMapAsync((map) => {
    let aMap: AMap = map;
  })
})

@Component
struct ButtonComponent {
  @Prop params: Params
  customView: AmapWidgetView = this.params.platformView as AmapWidgetView

  build() {
    Row() {
      MapViewComponent().width('100%').height('100%')
    }
  }
}

接下来创建一个 AmapWidgetFactory.ets

dart 复制代码
export class AmapWidgetFactory extends PlatformViewFactory {
  message: BinaryMessenger;

  constructor(message: BinaryMessenger, createArgsCodes: MessageCodec<Object>) {
    super(createArgsCodes);
    this.message = message;
  }

  public create(context: common.Context, viewId: number, args: Object): PlatformView {
    return new AmapWidgetView(context, viewId, args, this.message);
  }
}

最终需要创建一个 AmapWidgetPlugin.ets

dart 复制代码
export class AmapWidgetPlugin implements FlutterPlugin {
  getUniqueClassName(): string {
    return 'AmapWidgetPlugin';
  }

  onAttachedToEngine(binding: FlutterPluginBinding): void {
    binding.getPlatformViewRegistry()?.
    registerViewFactory('com.shaohushuo.app/customView', new AmapWidgetFactory(binding.getBinaryMessenger(), StandardMessageCodec.INSTANCE));
  }

  onDetachedFromEngine(binding: FlutterPluginBinding): void {}
}

插件创建好之后,记得在 EntryAbility 中注册插件

dart 复制代码
 this.addPlugin(new AmapWidgetPlugin())

需要注意的是,视图ID一定要两侧保持一致,如这里名为 'com.shaohushuo.app/customView',否则无法正常显示

截图

参考资料

相关推荐
小a杰.3 小时前
Flutter 与 AI 深度集成指南:从基础实现到高级应用
人工智能·flutter
萌虎不虎4 小时前
【在鸿蒙系统中实现拍照预览功能】
华为·harmonyos
萌虎不虎6 小时前
【鸿蒙实现显示屏测试实现方法】
华为·harmonyos
用户5951433221779 小时前
HarmonyOS应用开发之滚动容器Scroll
harmonyos
用户5951433221779 小时前
HarmonyOS应用开发之瀑布流、上拉加载、无限滚动一文搞定
harmonyos
用户5951433221779 小时前
鸿蒙应用开发之@Builder自定义构建函数:值传递与引用传递与UI更新
harmonyos
程序员老刘10 小时前
跨平台开发地图:客户端技术选型指南 | 2025年12月
flutter·客户端
不爱吃糖的程序媛10 小时前
Flutter 开发的鸿蒙AtomGit OAuth 授权应用
华为·harmonyos
一名普通的程序员11 小时前
使用 Flutter Pay 插件实现 Apple Pay 和 Google Pay 的完整指南
flutter
麦客奥德彪12 小时前
Flutter riverpod 对应Android开发概念理解
flutter