鸿蒙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',否则无法正常显示

截图

参考资料

相关推荐
好的佩奇5 小时前
Dart 之扩展方法
android·flutter·dart
好的佩奇7 小时前
蓝牙之经典蓝牙
android·flutter·蓝牙
传奇开心果编程9 小时前
【Flutter踩坑排雷】第19课:路由硬编码坑|字符串路由书写错误,页面跳转失败排查
android·flutter·ios·移动开发·跨平台·ui框架·声明式ui
行者-全栈开发10 小时前
【鸿蒙心迹】国际化 i18n 与多语言资源管理实战(HarmonyOS 7.x)
ui·华为·重构·国际化·harmonyos·多语言
OH_TPC12 小时前
HarmonyOS APP开发---"云客服"远程视频客服App,需要用到这个库
harmonyos
逆回1 天前
给鸿蒙手机做一只 3D 宠物:五个把我卡住的问题
harmonyos
钉先生贾1 天前
性能、体积与稳定性:怎样写出可信的适配结论
华为·harmonyos
Nerd(BUG版)1 天前
Flutter学习day5--事件手势与命中测试
学习·flutter
笑 总不会犯错1 天前
摆脱多端数据撕裂,鸿蒙分布式数据库同步与冲突合并
harmonyos
传奇开心果1 天前
【Flutter踩坑排雷】第5课:扩展方法冲突坑|同名扩展引发编译歧义,故障规避手段
android·flutter