diff --git a/lib/src/layer/label.dart b/lib/src/layer/label.dart new file mode 100644 index 000000000..9da9e388b --- /dev/null +++ b/lib/src/layer/label.dart @@ -0,0 +1,45 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; + +class Label { + static void paintText( + Canvas canvas, + List points, + String? labelText, + TextStyle? labelStyle, + ) { + var maxDx = 0.0; + var minDx = double.infinity; + var dx = points.map((e) => e.dx).toList().fold(0.0, + (previousValue, element) { + maxDx = max(maxDx, element); + minDx = min(minDx, element); + return previousValue + element; + }) / + points.length; + var dy = points.map((e) => e.dy).toList().fold( + 0.0, (previousValue, element) => previousValue + element) / + points.length; + + final textSpan = TextSpan(text: labelText, style: labelStyle); + final textPainter = TextPainter( + text: textSpan, + textAlign: TextAlign.center, + textDirection: TextDirection.ltr, + maxLines: 1, + ); + if (dx > 0) { + textPainter.layout(minWidth: 0, maxWidth: double.infinity); + dx = dx - textPainter.width / 2; + dy = dy - textPainter.height / 2; + + if (maxDx - minDx > textPainter.width) { + textPainter.paint( + canvas, + Offset(dx, dy), + ); + } + } + } +} diff --git a/lib/src/layer/polygon_layer.dart b/lib/src/layer/polygon_layer.dart index c1bbcaba0..201c880eb 100644 --- a/lib/src/layer/polygon_layer.dart +++ b/lib/src/layer/polygon_layer.dart @@ -3,6 +3,7 @@ import 'dart:ui'; import 'package:flutter/widgets.dart'; import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter_map/src/layer/label.dart'; import 'package:flutter_map/src/map/map.dart'; import 'package:latlong2/latlong.dart' hide Path; // conflict with Path from UI @@ -37,6 +38,8 @@ class Polygon { final bool isDotted; final bool isFilled; late final LatLngBounds boundingBox; + final String? label; + final TextStyle labelStyle; Polygon({ required this.points, @@ -47,6 +50,8 @@ class Polygon { this.disableHolesBorder = false, this.isDotted = false, this.isFilled = false, + this.label, + this.labelStyle = const TextStyle(), }) : holeOffsetsList = null == holePointsList || holePointsList.isEmpty ? null : List.generate(holePointsList.length, (_) => []); @@ -258,6 +263,15 @@ class PolygonPainter extends CustomPainter { canvas.drawPath(path, paint); _paintBorder(canvas); + + if (polygonOpt.label != null) { + Label.paintText( + canvas, + polygonOpt.offsets, + polygonOpt.label, + polygonOpt.labelStyle, + ); + } } }