如何在谷歌地图中将文本设置为标记
Posted
技术标签:
【中文标题】如何在谷歌地图中将文本设置为标记【英文标题】:How to set a text as Marker in Google Maps 【发布时间】:2021-08-23 19:36:59 【问题描述】:嘿,我正在尝试在地图中显示文本。因此,我使用 textpainter 来“绘制”给定的字符串并将其添加为标记。现在有我的问题:我知道标记的图标应该是 BitmapDescriptor,但我不知道如何将返回的 textpainter 的“图片”转换为 BitmapDescriptor。
class MapAction extends StatefulWidget
MapAction(Key key, this.inputText) : super(key: key);
final String inputText;
@override
_MapActionState createState() => _MapActionState();
class _MapActionState extends State<MapAction>
Set<Circle> _circles = Set();
Set<Marker> _marker = Set();
int counter1 = 0;
int counter2 = 0;
void setMarker(LatLng position) async
counter2++;
Marker tmp = Marker(
//icon: How can I set my "inputText" as Marker
markerId: MarkerId("$counter2"),
position: position);
setState(()
_marker.add(tmp);
);
@override
Widget build(BuildContext context)
return StreamBuilder<Position>(
stream: GeolocatorService().getCurrentLocation(),
builder: (context, snapshot)
if (!snapshot.hasData)
return Container(
height: MediaQuery.of(context).size.height / 2,
width: MediaQuery.of(context).size.width,
child: CircularProgressIndicator());
else
return Container(
height: MediaQuery.of(context).size.height / 2,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
markers: _marker,
initialCameraPosition: CameraPosition(
target: LatLng(
snapshot.data.latitude, snapshot.data.longitude),
zoom: 16.0),
zoomControlsEnabled: false,
//mapType: MapType.satellite,
myLocationButtonEnabled: true,
myLocationEnabled: true,
));
);
class MyPainter extends CustomPainter
MyPainter(this.inputText);
final String inputText;
@override
void paint(Canvas canvas, Size size)
final textStyle = TextStyle(
color: Colors.black,
fontSize: 30,
);
final textSpan = TextSpan(
text: inputText,
style: textStyle,
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(
minWidth: 0,
maxWidth: size.width,
);
final xCenter = (size.width - textPainter.width) / 2;
final yCenter = (size.height - textPainter.height) / 2;
final offset = Offset(xCenter, yCenter);
textPainter.paint(canvas, offset);
@override
bool shouldRepaint(CustomPainter old)
return false;
我知道我可以显示绘制的文本:
CustomPaint(size: Size(300, 300),
painter: MyPainter(inputText: inputText),
),
那么有没有一种方法或类似的东西可以将此 CustomPaint-Widget 转换为 BitmapDescriptor?
【问题讨论】:
【参考方案1】:尝试使用 PictureRecorder 输出图像:
ui.PictureRecorder recorder = ui.PictureRecorder();
MyPainter painter = MyPainter(inputText: 'blablabla');
return recorder.endRecording()
.toImage(painter.size.width.floor(), painter.size.height.floor());
然后改成字节显示谷歌地图图片:
var pngBytes = await image.toByteData(format: ui.ImageByteFormat.png)
【讨论】:
以上是关于如何在谷歌地图中将文本设置为标记的主要内容,如果未能解决你的问题,请参考以下文章