当前位置: 首页 > article >正文

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

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

完整代码见 Flutter 鸿蒙版 Demo

概述

Dart 侧

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

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


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;
  })
})


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

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

接下来创建一个 AmapWidgetFactory.ets

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

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 中注册插件

 this.addPlugin(new AmapWidgetPlugin())

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

截图

参考资料

  • 如何使用PlatformView
  • PlatformView同层渲染新方案

http://www.kler.cn/a/611898.html

相关文章:

  • AG7220替代方案|ASL6328芯片设计|HDMI2.0 Retimer中继器方案
  • 核函数(机器学习深度学习)
  • win11+ubuntu双系统安装
  • 【解决】Linux命令报错:Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64
  • Python爬虫:Asyncpy 的详细使用和案例(高性能异步爬虫框架)
  • 安装node,配置npm, yarn, pnpm, bun
  • [Synth 8-439] module ‘xpm_fifo_async‘ not found
  • xr-frame 用cube代替线段实现两点间的连线
  • 蓝桥杯练习题--一年中的第几天
  • 【AVRCP】AVRCP核心术语解析
  • 第4章 IP网络扫描(网络安全评估)
  • 音乐极客指南:Melody高音质私有云音乐平台本地部署方案
  • 【Ubuntu设备端口绑定】
  • 深入理解指针(4)(C语言版)
  • 视频格式转换:畅享多平台无缝视频体验
  • 4.用 Excel 录入数据
  • AI大模型使用记录
  • 【2025全网最新最全】前端Vue3框架的搭建及工程目录详解
  • 泛目录程序,无极泛目录是如何搭建强大站群的?
  • SQL Server 动态构建 SQL 语句学习指南