You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Google Maps中为Polygon添加名称/ID标签

在Flutter Google Maps中为多边形添加中心标签的实现方案

因为Google Maps Flutter的Polygon类本身不支持InfoWindow,最简便的实现方式是在多边形中心点添加一个无图标的Marker,用Marker的InfoWindow来显示多边形名称,具体步骤如下:

1. 实现多边形中心点计算方法

首先根据多边形的顶点坐标计算中心点,这里采用坐标平均值算法(适用于大多数凸多边形场景):

LatLng calculatePolygonCenter(List<LatLng> points) {
  double totalLat = 0.0;
  double totalLng = 0.0;
  
  for (final point in points) {
    totalLat += point.latitude;
    totalLng += point.longitude;
  }
  
  return LatLng(totalLat / points.length, totalLng / points.length);
}

2. 同步创建多边形与对应标签Marker

在你原有的多边形创建逻辑中,为每个多边形生成一个无图标的Marker,将其定位到中心点并绑定InfoWindow:

// 假设你维护了多边形和标记的列表
List<Polygon> polygons = [];
List<Marker> markers = [];

for (int i = 0; i < zones.length; i++) {
  final zone = zones[i];
  
  // 添加多边形
  polygons.add(Polygon(
    polygonId: PolygonId(zone.name),
    points: zone.points,
    fillColor: Colors.black.withOpacity(0.3),
    strokeColor: Colors.black,
    geodesic: true,
    strokeWidth: 4,
  ));
  
  // 计算中心点并添加无图标标签Marker
  final center = calculatePolygonCenter(zone.points);
  markers.add(Marker(
    markerId: MarkerId('zone-label-${zone.name}'), // 唯一ID避免冲突
    position: center,
    infoWindow: InfoWindow(title: zone.name),
    // 设置透明图标,只保留InfoWindow交互
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueTransparent),
  ));
}

3. 将列表传入GoogleMap组件

最后把polygons和markers列表赋值给GoogleMap组件的对应属性即可:

GoogleMap(
  // 其他配置项...
  polygons: Set<Polygon>.of(polygons),
  markers: Set<Marker>.of(markers),
)

补充说明

  • 如果是凹多边形需要更精确的中心点,可以改用多边形重心计算算法,但平均值在绝大多数业务场景下足够使用。
  • 若需要默认显示InfoWindow而非点击触发,可以给Marker的infoWindow添加visible: true属性。

内容的提问来源于stack exchange,提问作者César Sotillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:05:13