在flutter谷歌地图中标记点的自定义加载格式只允许assets本地资源图片和byte数组的格式,此byte在flutter中应为Uint8List。
以下方法步骤只针对前端上传自定义标记点到后端再渲染到谷歌地图的案例。
1、前端在相册选择要上传的后端的图片,和本地资源库中的图标组合成自己想要的标记点图片样式:
///组装图片组件
Widget startImageWidget() {
return GetBuilder<CreateEventLogic>(
id: 'img',
builder: (logic) {
return RepaintBoundary(
key: state.startKey,
child: Container(
width: 124.w,
height: 139.w,
alignment: Alignment.topCenter,
padding: EdgeInsets.only(top: 28.w),
decoration: BoxDecoration(
image: DecorationImage(
image: ImageUtils.getAssetImage('common/icon30'))),
child: LoadNetWorkImage(
url: state.imgUrl11,
width: 58.w,
height: 58.w,
isPeople: true,
),
),
);
});
}
RepaintBoundary 是关键点,RepaintBoundary组件可以将其包裹的其它组件截图转换成字节图片格式Uint8List。其中 key: state.startKey,则是获取组件信息的关键 该key的类型是GlobalKey
///将组装的图片转成base64
convertUint8ListImage() async {
// 获取当前RenderObject
RenderRepaintBoundary startBoundary = state.startKey.currentContext
?.findRenderObject() as RenderRepaintBoundary;
// 创建图像
ui.Image? image1 = await startBoundary.toImage(pixelRatio: 1.0);
// 将图像编码为PNG
ByteData? byteData1 =
await image1.toByteData(format: ui.ImageByteFormat.png);
// 将ByteData转为Uint8List
Uint8List? pngBytes1 = byteData1?.buffer.asUint8List();
state.startImg = base64.encode(pngBytes1!);
}
2、通过接口传给后端,传给后端时需要先将Uint8List格式的图片转成base64格式。
base64.encode()
3、通过接口数据渲染至地图,渲染时需要将base64格式的图片转成Uint8List
base64Decode()
4、渲染标记点
Set<Marker> markers = {};
markers.add(
Marker(
markerId: const MarkerId('myMarker'),
position: position ?? baseState.myLocation,
icon: BitmapDescriptor.bytes(result, width: 23.w, height: 27.w),
onTap: () {
Get.toNamed(RouterPath.userInfo,
arguments: {'id': baseState.userDetails['id']});
}),
);