当前位置: 首页 > 知识库问答 >
问题:

如何在Flutter中自定义谷歌地图标记图标

柯甫
2023-03-14

我在我的flutter应用程序中使用google_maps_flutter来使用谷歌地图我有自定义标记图标,我用BitmapDescriptor.from字节(mark erIcon)加载它,但我想用一些文本显示Url的图标。

Map<MarkerId, Marker> markers =
  <MarkerId, Marker>{}; // CLASS MEMBER, MAP OF MARKS

void _add([center]) async {


for (int i = 0; i < sallersList.length; i++) {
  if (sallersList[i]["uID"] != currentUser.uid) {
    /*var request = await http.get(sallersList[i]["user_image"]);
    var bytes = await request.bodyBytes;*/

     final Uint8List markerIcon = await getBytesFromCanvas(150,         150);

    var markerIdVal = sallersList[i]["uID"];
    final MarkerId markerId = MarkerId(markerIdVal);

    // creating a new MARKER
    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(
          sallersList[i]["latitude"], //+ sin(1 * pi / 6.0) / 20.0,
          sallersList[i]["longitude"] //+ cos(1 * pi / 6.0) / 20.0,
          ),
      // icon: BitmapDescriptor.fromBytes(bytes.buffer.asUint8List(),),
      icon: BitmapDescriptor.fromBytes(markerIcon),
      infoWindow: InfoWindow(
          title: sallersList[i]["user_name"],
          snippet: sallersList[i]["address"]),
      onTap: () {
       // print(sallersList[i]["uID"]);

        Navigator.of(context).push(new MaterialPageRoute(
            builder: (BuildContext context) =>
            new DirectDetails()));
      },
    );
    if (this.mounted)
      setState(() {
        // adding a new marker to map
        markers[markerId] = marker;
      });
  }
}
}


Future<Uint8List> getBytesFromCanvas(int width, int height) async  {
final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
final Canvas canvas = Canvas(pictureRecorder);
final Paint paint = Paint()..color = Colors.blue;
final Radius radius = Radius.circular(width/2);
canvas.drawRRect(
    RRect.fromRectAndCorners(
      Rect.fromLTWH(0.0, 0.0, width.toDouble(),  height.toDouble()),
      topLeft: radius,
      topRight: radius,
      bottomLeft: radius,
      bottomRight: radius,
    ),
    paint);

TextPainter painter = TextPainter(textDirection: TextDirection.ltr);
painter.text = TextSpan(
  text: '1',
  style: TextStyle(fontSize: 65.0, color: Colors.white),
);

painter.layout();
painter.paint(
    canvas,
    Offset((width * 0.5) - painter.width * 0.5,
        (height * .5) - painter.height * 0.5));
final img = await pictureRecorder.endRecording().toImage(width, height);
final data = await img.toByteData(format: ui.ImageByteFormat.png);
return data.buffer.asUint8List();
}

这就是我们要达到的目的

是否可以通过flutter或任何可以动态创建图像的外部图像依赖来实现相同的效果。

共有2个答案

杨志强
2023-03-14
  1. 使用图像包,https://pub.dev/packages/image,作为im
  2. 下载图像文件f=wait_downloadFile(url,"边框"); im. Image img=im.decodeImage(f.readAsBytesSync());
  3. 使用DrawString()在上面写数字
  4. BitmapDescriptor.from字节(im.encodePng(img))

静态var httpClient=新的httpClient();

Future<File> _downloadFile(String url, String filename) async {
    var request = await httpClient.getUrl(Uri.parse(url));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    return file;
  }
申屠无尘
2023-03-14

要实现上述休闲造型步骤,请遵循以下步骤:

  1. 导入程序包
import 'dart:async';
import 'dart:ui' as ui;
import 'dart:typed_data';
import 'dart:io';
import 'package:flutter/material.dart';
Future<ui.Image> getImageFromPath(String imagePath) async {
    File imageFile = File(imagePath);

    Uint8List imageBytes = imageFile.readAsBytesSync();

    final Completer<ui.Image> completer = new Completer();

    ui.decodeImageFromList(imageBytes, (ui.Image img) {
      return completer.complete(img);
    });

    return completer.future;
}
Future<BitmapDescriptor> getMarkerIcon(String imagePath, Size size) async {
    final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(pictureRecorder);

    final Radius radius = Radius.circular(size.width / 2);

    final Paint tagPaint = Paint()..color = Colors.blue;
    final double tagWidth = 40.0;

    final Paint shadowPaint = Paint()..color = Colors.blue.withAlpha(100);
    final double shadowWidth = 15.0;

    final Paint borderPaint = Paint()..color = Colors.white;
    final double borderWidth = 3.0;

    final double imageOffset = shadowWidth + borderWidth;

    // Add shadow circle
    canvas.drawRRect(
        RRect.fromRectAndCorners(
          Rect.fromLTWH(
              0.0,
              0.0,
              size.width,
              size.height
          ),
          topLeft: radius,
          topRight: radius,
          bottomLeft: radius,
          bottomRight: radius,
        ),
        shadowPaint);

    // Add border circle
    canvas.drawRRect(
        RRect.fromRectAndCorners(
          Rect.fromLTWH(
              shadowWidth,
              shadowWidth,
              size.width - (shadowWidth * 2),
              size.height - (shadowWidth * 2)
          ),
          topLeft: radius,
          topRight: radius,
          bottomLeft: radius,
          bottomRight: radius,
        ),
        borderPaint);

    // Add tag circle
    canvas.drawRRect(
        RRect.fromRectAndCorners(
          Rect.fromLTWH(
              size.width - tagWidth,
              0.0,
              tagWidth,
              tagWidth
          ),
          topLeft: radius,
          topRight: radius,
          bottomLeft: radius,
          bottomRight: radius,
        ),
        tagPaint);

    // Add tag text
    TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr);
    textPainter.text = TextSpan(
      text: '1',
      style: TextStyle(fontSize: 20.0, color: Colors.white),
    );

    textPainter.layout();
    textPainter.paint(
        canvas,
        Offset(
            size.width - tagWidth / 2 - textPainter.width / 2,
            tagWidth / 2 - textPainter.height / 2
        )
    );

    // Oval for the image
    Rect oval = Rect.fromLTWH(
        imageOffset,
        imageOffset,
        size.width - (imageOffset * 2),
        size.height - (imageOffset * 2)
    );

    // Add path for oval image
    canvas.clipPath(Path()
      ..addOval(oval));

    // Add image
    ui.Image image = await getImageFromPath(imagePath); // Alternatively use your own method to get the image
    paintImage(canvas: canvas, image: image, rect: oval, fit: BoxFit.fitWidth);

    // Convert canvas to image
    final ui.Image markerAsImage = await pictureRecorder.endRecording().toImage(
        size.width.toInt(),
        size.height.toInt()
    );

    // Convert image to bytes
    final ByteData byteData = await markerAsImage.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List uint8List = byteData.buffer.asUint8List();

    return BitmapDescriptor.fromBytes(uint8List);
}
final Marker marker = Marker(
      icon: await getMarkerIcon("path/to/your/image.png", Size(150.0, 150.0))
);

注意:带有数字的标签是“松散”放置的,用于演示目的-您可能需要使用不同的样式,以便它随内容扩展。

 类似资料:
  • 我正在为Android制作基于谷歌地图服务的公共交通地图。地图应该包含很多标记(超过300个),它们应该在地图放大和缩小(缩放)时调整大小。现在标记只是互相重叠,有没有办法创建像这样的自定义标记? 我自己也试过,但没有成功。使用android-map-utils库(https://github.com/googlemaps/android-maps-utils)标记现在看起来更好了,但它们不能调整

  • 我想更改Google Maps上选定的标记图标,因此我有以下代码: 在这一行,我从下面得到错误: 例外情况如下:

  • 我需要一些帮助来绘制我正在绘制的地图。地图并不特别复杂,因为我是一个初学者,我有一堆带有信息窗口的标记(完成后还会有更多标记),单击标记或选择页面HTML端下拉菜单的相应项时可以打开这些标记。 当信息窗口打开时(在HTML菜单中单击或选择),我想做但自己找不到的是在地图上自动居中标记。我假设有某种函数可以分配给click或infowindow打开事件,但无法确定是哪种函数以及如何实现它。 我的代码

  • 我们如何能实现一个地图标记图标与矢量资产文件,谷歌显示的方式是这样的,编程: 更新: 这在处理向量资源时不起作用。问这个问题的主要原因。上述代码中的错误: java.lang.非法参数异常:解码图像失败。提供的图像必须是位图。

  • 所以我正在准备一个页面,其中有一个谷歌地图,有两个形式,即纬度和经度,和一个提交按钮。

  • 情况是我使用Fragments在main活动中显示2个视图,这意味着我有两个选项卡,而在第二个选项卡中,我使用以下代码显示谷歌地图 这是第二个选项卡,我想自定义地图,为此我在上面的函数中使用了这段代码。 imap=SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map))。getMap(); imap是在创建