flutterdartgoogle-mapsgoogle-maps-markersgoogle-maps-flutter

Flutter how to toggle markers visibility in google maps


How can I toggle the visibility of list of markers in goole maps using a FloatingActionButton? Alternatively, a switch button should also work.

This is my function to add the markers:

void addAll() async {
    _markers = Set<Marker>();
    int i = 0;
    if(_markerList.length > 0) {
      for (i = 0; i < _markerList.length; i++) {
        _markers.add(Marker(
            markerId: MarkerId(i.toString()),
            position: LatLng(_markerList[i].latitude!,
                _markerList[i].longitude!),
            icon: BitmapDescriptor.fromBytes(markerIcon!),
        ));
      //}
      }
    }
    setState(() {});
  }

I manage the visibility with a variable:

bool isVisible = true;

And here is my FloatingActionButton where I'd like to manage the visibility:

Padding(
   padding: EdgeInsets.all(16.0),
   child: Align(
      alignment: Alignment.bottomRight,
      child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[
         Builder(
            builder: (context) => FloatingActionButton(
               child: Icon(Icons.location_pin),
               onPressed: () {
                  isVisible ? isVisible = false : isVisible = true;
                  if(isVisible){
                     //Create the the new visible marker list here
                  }
                  else {
                     //Create the the new non visible marker list here
                  }
               }),
            ),
       ])),
   )

Solution

  • To remove a specific marker, just pass the marker id. It will find if it is available and remove it or else do nothing:

    Marker marker = _markers.firstWhere((marker) => marker.markerId.value == "your_marker_id",orElse: () => null);
    setState(() {
       _markers.remove(marker); 
    });
    

    To remove all markers, just assign empty Map to your markers variable:

    setState(() {
       _markers = {};
     });