You need to enable JavaScript to run this app. 如何在Flutter的flutter_polyline_points折线上放置Widget显示距离与预计时间
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的flutter_polyline_points折线上放置Widget显示距离与预计时间

实现方案

方案1:自定义Marker实现(最简便,适配地图原生交互)

你直接把要展示的距离/时间面板做成自定义Marker,固定在折线的中点位置即可,不需要额外处理地图层级关系,步骤如下:

  1. 先实现Widget转Bitmap的工具方法,用于把自定义的展示面板转成Marker可用的图标:
import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';

Future<BitmapDescriptor> widgetToBitmap(
  Widget widget, {
  Size size = const Size(200, 60),
}) async {
  final repaintBoundary = RepaintBoundary(
    child: Material(
      color: Colors.transparent,
      child: widget,
    ),
  );
  final renderObject = repaintBoundary.createRenderObject(ui.PlatformDispatcher.instance.views.first);
  renderObject.layout(BoxConstraints.tight(size));
  final image = await renderObject.toImage(pixelRatio: ui.PlatformDispatcher.instance.views.first.devicePixelRatio);
  final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
  return BitmapDescriptor.fromBytes(bytes!.buffer.asUint8List());
}
  1. 在你现有的_addPolyLine方法中,计算折线中点,添加自定义Marker:
_addPolyLine(List<LatLng> polylineCoordinates) async {
  PolylineId id = PolylineId("poly");
  Polyline polyline = Polyline(
    polylineId: id,
    color: Colors.deepOrange,
    points: polylineCoordinates,
    width: 3,
    patterns: [PatternItem.dash(15), PatternItem.gap(10)],
  );
  polylines[id] = polyline;

  // 计算折线中点坐标
  LatLng midPoint;
  if (polylineCoordinates.length % 2 == 0) {
    final p1 = polylineCoordinates[polylineCoordinates.length ~/ 2 -1];
    final p2 = polylineCoordinates[polylineCoordinates.length ~/ 2];
    midPoint = LatLng((p1.latitude + p2.latitude)/2, (p1.longitude + p2.longitude)/2);
  } else {
    midPoint = polylineCoordinates[polylineCoordinates.length ~/2];
  }

  // 生成自定义面板的Marker图标
  final infoIcon = await widgetToBitmap(
    Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 4, spreadRadius: 1)],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("${distance}km", style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
          Text("约${duration}分钟", style: const TextStyle(fontSize: 12, color: Colors.grey)),
        ],
      ),
    )
  );

  // 添加信息Marker到markers集合,zIndex设置高一点避免被普通Marker遮挡
  final infoMarkerId = MarkerId("route_info");
  final infoMarker = Marker(
    markerId: infoMarkerId,
    position: midPoint,
    icon: infoIcon,
    zIndex: 10,
    infoWindow: InfoWindow.noText,
  );
  markerData[infoMarkerId] = infoMarker;

  setState(() {});
}

这种方式的好处是面板会跟着地图原生的缩放、拖动、旋转自动适配位置,不需要额外写监听逻辑。

方案2:Stack叠加Flutter原生Widget(交互更灵活)

如果你的面板需要支持点击、长按等复杂交互,可以用Stack把GoogleMap和自定义面板叠加,通过坐标转换定位面板位置:

  1. 布局结构调整:
Stack(
  children: [
    GoogleMap(
      // 你原有的GoogleMap配置不变
      onCameraMove: (position) {
        // 地图拖动缩放时更新面板位置
        _updateInfoPanelPosition();
      },
    ),
    if(_midPoint != null) Positioned(
      left: _panelOffset.dx,
      top: _panelOffset.dy,
      child: GestureDetector(
        onTap: () {
          // 可以自定义点击事件
        },
        child: Container(
          // 你要显示的距离时间面板样式
        ),
      ),
    )
  ],
)
  1. 实现坐标转换逻辑:
Offset _panelOffset = Offset.zero;
LatLng? _midPoint;

_updateInfoPanelPosition() async {
  if(_midPoint == null || _mapController == null) return;
  final screenCoordinate = await _mapController!.getScreenCoordinate(_midPoint!);
  setState(() {
    // 减去面板宽高的一半,让面板居中显示在中点上方
    _panelOffset = Offset(
      screenCoordinate.x.toDouble() - 100, // 100是面板宽度的一半
      screenCoordinate.y.toDouble() - 70, // 70是面板高度加上偏移量,避免挡住折线
    );
  });
}

在_addPolyLine方法中给_midPoint赋值之后调用一次_updateInfoPanelPosition初始化位置即可。


内容的提问来源于stack exchange,提问作者Musthafa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 11:06:08