Alessandro Verona
Alessandro Verona

Reputation: 1257

Place a custom text under Marker _icon in Flutter Google Maps Plugin

I'm trying to add some text to a custom marker (I'm using google maps flutter)

var cluster =  Marker(
                markerId: MarkerId( uuid.v1() ),
                position: new LatLng(clusterMap[box].latitude,clusterMap[box].longitude ),
                icon: _clusterImage,
                alpha: 0.5);

What can I do is only to change the Icon, now the icon is a circle with a grey background. I want to add some text in this circle. There is a way to do that?

Upvotes: 2

Views: 3130

Answers (2)

Nirmal Scaria
Nirmal Scaria

Reputation: 611

The right (but messy) way is to use Canvas and do the painting manually. But if you just want text on marker, as a label (or a tag), this should do the job.

https://pub.dev/packages/label_marker

Use it as follows

markers.addLabelMarker(LabelMarker(
    label: "TextToShow",
    markerId: MarkerId("idString"),
    position: LatLng(10.0, 11.0),
    backgroundColor: Colors.green,
    )).then((value) {
    setState(() {});
    },
);

Upvotes: 2

You need to use canvas to write on marker. This function writes on the marker. After adding those lines to your class, go down below.

import 'package:flutter/material.dart'; 
import 'package:flutter/painting.dart'; 
import 'package:google_maps_flutter/google_maps_flutter.dart'; 
import 'dart:async'; 
import 'dart:typed_data'; 
import 'dart:ui' as ui; 

....... .......
Future<Uint8List> getBytesFromCanvas(String text) async {

    final ui.PictureRecorder pictureRecorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(pictureRecorder);
    final Paint paint1 = Paint()..color = Colors.grey;
    final int size = 100; //change this according to your app
    canvas.drawCircle(Offset(size / 2, size / 2), size / 2.0, paint1);
    TextPainter painter = TextPainter(textDirection: TextDirection.ltr);
    painter.text = TextSpan(
      text: text,//you can write your own text here or take from parameter
      style: TextStyle(
          fontSize: size / 4, color: Colors.black, fontWeight: FontWeight.bold),
    );
    painter.layout();
    painter.paint(
      canvas,
      Offset(size / 2 - painter.width / 2, size / 2 - painter.height / 2),
    );

    final img = await pictureRecorder.endRecording().toImage(size, size);
    final data = await img.toByteData(format: ui.ImageByteFormat.png);
    return data.buffer.asUint8List();
  }

Now, you can easily call marker that you desired with following.

final Uint8List desiredMarker =
      await getBytesFromCanvas('Write What You want!!');

      var cluster =  Marker(
                markerId: MarkerId( uuid.v1() ),
                position: new LatLng(clusterMap[box].latitude,clusterMap[box].longitude ),
                icon: BitmapDescriptor.fromBytes(desiredMarker),
                alpha: 0.5);

I hope this is helpful. Take care.

Upvotes: 6

Related Questions