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

截图

参考资料

相关推荐
OH_TPC3 小时前
【鸿蒙优选三方库】@ohos/aki:一行代码让 ArkTS 调 C++
harmonyos
垆边人似月.3 小时前
华为机试题 :最长递增子序列题目
数据结构·c++·算法·华为
wenyiyiyiyiyi3 小时前
我用鸿蒙 ArkTS 写了个自己天天用的备忘录:待办、课表和长期目标,全塞进一块桌面卡片
harmonyos
恋猫de小郭5 小时前
Genkit Dart 1.0 发布,Flutter 原生的 AI Agent 终于完整了
android·前端·flutter
第10086个小白5 小时前
flutter桌面端打包方式(Inno Setup Compiler)版本
前端·flutter
承渊政道6 小时前
鸿蒙设备远控电脑实测:ToDesk蓝牙键鼠、双模式鼠标、跨端剪贴板,远控电脑更顺手了
计算机外设·电脑·harmonyos·远程工作·todesk
CV工程师丁Sir8 小时前
ArkWeb 手记 04|DevTools 调试与缓存清理
java·spring·缓存·harmonyos
程序猿追20 小时前
HarmonyOS 6 上做个极简浏览器:Web 组件 + 前进后退 + 加载进度
前端·华为·harmonyos
程序猿追20 小时前
HarmonyOS 6 音视频实战:用 AVPlayer 做一个本地音乐播放器
华为·音视频·harmonyos
威哥爱编程20 小时前
HarmonyOS 7 多设备 UX 自动检测实战:AppAnalyzer 多设备体检 + 一多工程底线,提前拦截截断重叠大图大字
harmonyos