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

如何在Flutter的Google Map中实现指定折线动画(附代码)

实现地图轨迹逐点绘制动画的修改方案

你需要实现的是轨迹从起点到终点逐步绘制的动态效果,现有代码没有利用动画控制器来控制轨迹的显示进度,以下是具体修改步骤:

核心修改思路

  1. 调整动画与数据请求的嵌套顺序,避免动画帧触发重复请求Marker
  2. 根据动画进度动态截取轨迹点,实现逐段绘制效果

修改后的完整代码

_renderMap() {
  // 外层用FutureBuilder获取Marker,避免动画刷新重复请求
  return FutureBuilder<Set<Marker>>(
    future: _getTowerMarkers(),
    initialData: const <Marker>{},
    builder: (context, snapshot) {
      // 内层用AnimatedBuilder响应动画变化
      return AnimatedBuilder(
        animation: _animation!,
        builder: (BuildContext context, Widget? child) {
          // 根据动画进度计算要显示的轨迹点数量
          final int progressCount = (_animation!.value * latLen.length).floor();
          // 截取对应数量的轨迹点
          final List<LatLng> animatedLatLen = latLen.take(progressCount).toList();

          return SizedBox(
            height: 200,
            width: MediaQuery.of(context).size.width,
            child: GoogleMap(
              mapType: MapType.normal,
              zoomControlsEnabled: true,
              initialCameraPosition: CameraPosition(
                target: LatLng(
                  _attendanceViewModel.coordinatesList![0].latitude!,
                  _attendanceViewModel.coordinatesList![0].longitude!),
                zoom: 9.0,
              ),
              onMapCreated: (GoogleMapController controller) {
                _controller.complete(controller);
              },
              markers: snapshot.data!,
              polylines: {
                Polyline(
                  polylineId: const PolylineId("route"),
                  points: animatedLatLen, // 使用动态截取的轨迹点
                  width: 5,
                  patterns: const [PatternItem.dot, PatternItem.dot],
                  startCap: Cap.roundCap,
                  endCap: Cap.roundCap,
                  color: AppColors.green,
                )
              },
            ),
          );
        },
      );
    },
  );
}

额外注意事项

  • 确保你的_animation是正确初始化的线性动画,示例初始化代码参考:
    late AnimationController _animationController;
    late Animation<double> _animation;
    
    @override
    void initState() {
      super.initState();
      _animationController = AnimationController(
        duration: const Duration(seconds: 3), // 调整动画时长
        vsync: this,
      );
      _animation = Tween<double>(begin: 0, end: 1).animate(_animationController);
      // 启动动画
      _animationController.forward();
    }
    
    @override
    void dispose() {
      _animationController.dispose();
      super.dispose();
    }
    
  • 如果轨迹点数量较多,可以调整动画时长来控制绘制速度
  • 若需要重复播放动画,可以在动画结束时调用_animationController.repeat()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:23:18