Change color of polylines on it's click in flutter
Here is how you can change the Polyline
color on tap:
First, you will need to define your Polyline
object as a collection of key/value pairs using the Map<>
class, this will help you later on identifying which polyline is being clicked/tapped on, specially if you have many Polyline
objects.
Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};
var pointArray; // var to hold the PolylineOverview
int _polylineIdCounter = 1; // polylineId that you will use for your polylines
Then, you can set your polylines like this:
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
});
}
From the above code, consumeTapEvents
is set to true
to make polylines recognize tap events. Then, on the onTap
method you will need a function that will handle the changing of color which should be like this:
_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
});
}
Lastly, you can add your polyline list to the GoogleMap()
widget like this:
GoogleMap(
...
polylines: Set<Polyline>.of(_polylines.values),
...
),
neha
Updated on December 24, 2022Comments
-
neha over 1 year
I created a polyline in flutter using flutter polyline plugin. Now I want to change the color of the polyline when user taps on it. Please help me in achieving this.
-
Adithya Shetty over 3 yearsyeah, you would have to rebuild a the polyline list and then pass it to a function
PolylineUpdates
the implementation file of the google-maps plugin.import 'package:google_maps_flutter_platform_interface/src/types/polyLine_updates.dart'
hopefully this is the import statement, if not you would have to search the files. you can follow this link for help pub.dev/documentation/google_maps_flutter_platform_interface/… -
Adithya Shetty over 3 yearsHappy to help!!!
-
-
neha over 3 yearsHow to do this for multiple routes? I am having list of multiple routes.