google-maps - 在 flutter 中单击时更改折线的颜色

标签 google-maps flutter dart polyline

我使用 flutter polyline 插件在 flutter 中创建了一条折线。现在我想在用户点击折线时更改折线的颜色。请帮助我实现这一目标。

最佳答案

以下是更改 Polyline 的方法点击颜色:

首先,您需要定义您的Polyline使用Map<>作为键/值对集合的对象class ,这将帮助您稍后识别正在单击/点击的多段线,特别是如果您有许多 Polyline对象。

  Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};

  var pointArray; // var to hold the PolylineOverview
  int _polylineIdCounter = 1; // polylineId that you will use for your polylines

然后,您可以像这样设置折线:

void _setPolyline() {
   pointArray = myPoints.decode(overviewPolylinePointsExample); // use PolyUtil(); to decode polylines

   final String polylineIdVal = 'marker_id_$_polylineIdCounter';
   _polylineIdCounter++;
   final PolylineId polylineId = PolylineId(polylineIdVal);

   final Polyline polyline = Polyline(
       polylineId: polylineId,
       consumeTapEvents: true, // Set to true to make polylines recognize tap events
       points: pointArray,
       color: Colors.red,
       onTap: () {
         _handlePolylineTap(polylineId); // function that will handle the color change and will be triggered when the polyline was tapped
    });

   setState(() {
     _polylines[polylineId] = polyline; // Add the polyline to your collection
   });
}

从上面的代码来看,consumeTapEvents设置为true使折线识别点击事件。然后,在 onTap方法,你将需要一个函数来处理颜色的变化,应该是这样的:

_handlePolylineTap(PolylineId polylineId) {
    setState(() {
       final Polyline newPolyline =
            _polylines[polylineId].copyWith(colorParam: Colors.blue); // create a new polyline object which has a different color using the colorParam property
       _polylines[polylineId] = newPolyline; // add that new polyline object to the list
     });
}

最后,您可以将折线列表添加到 GoogleMap()像这样的小部件:

GoogleMap(
    ...
    polylines: Set<Polyline>.of(_polylines.values),
    ...
),

关于google-maps - 在 flutter 中单击时更改折线的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64041116/

相关文章:

android - 如何在步行模式下打开谷歌地图

javascript - 我想制作一张世界地图,人们点击我的网站就像 Spark 一样。最好的方法是什么?

flutter - 为什么在 StatefulWidget 中没有定义 build 方法?

Flutter : local_auth: ^0. 6.1 : PlatformException(error, 您需要在此事件中使用 Theme.AppCompat 主题(或后代)。, null)

flutter - GraphQl Flutter 包设置中的缓存以及如何检查其工作情况

javascript - 无法拖动/缩放/与 Google map 交互

ios - 使用 Swift 在 Google map 中获取位置详细信息

user-interface - Flutter TabBarView 子项因高度无限制无法渲染

Flutter 使用 auto_route 删除所有路由

dart - 如何垂直扩展具有一个ListView的ListView