Search code examples
fluttergoogle-maps-markers

How to remove all my markers and add new ones onPress?


I want to show trails markers and change to Events markers and back when pressing a button. When i clear the markers, the size is 0, but they are not removed from the map. So when i add the new ones, nothing happens.

My initState

@override
void initState() {
    super.initState();
    _listToMarkersTrails();
    isTrailsMode = true;
    message = "Go to Events";
}

My map in a stack

Stack(
    children: <Widget>[
      map,
      Positioned(top: 5, right: 5, child: _getButton())
    ],
  ),

My _getbutton() method

RaisedButton _getButton() {
    if (isTrailsMode) {
      return RaisedButton(
        color: Colors.green,
        onPressed: () => _changeMarkers(),
        child: Text("Change to Events"),
      );
    } else {
      return RaisedButton(
        color: Colors.blue,
        onPressed: () => _changeMarkers(),
        child: Text("Change to Trails"),
      );
    }
  }

My _changeMarkers() method

void _changeMarkers() {
    setState(() => map.markers.clear());
    if (isTrailsMode) _listToMarkersTrails();
    else _listToMarkersEvents();
    setState(() => isTrailsMode = !isTrailsMode);
  }

My listToMarkers- methods

void _listToMarkersTrails() {
  for (var i = 0; i < widget.trailList.length; i++) {
    setState(() {
  map.markers.add(Marker(
    icon: BitmapDescriptor.defaultMarkerWithHue(50.0),
    infoWindow: InfoWindow(
        title: widget.trailList[i].trailName,
        onTap: () => _navigateToTrail(widget.trailList[i])),
    markerId: MarkerId("id{$i}_trails"),
    position: widget.trailList[i].markers[0].position,
  ));
  });
}  
}

void _listToMarkersEvents() {
for (var i = 0; i < widget.eventList.length; i++) {
  setState(() {
    map.markers.add(Marker(
      icon: BitmapDescriptor.defaultMarkerWithHue(150.0),
      infoWindow: InfoWindow(
          title: widget.eventList[i].date,
          onTap: () => _navigateToEvent(widget.eventList[i])),
      markerId: MarkerId("id{$i}_events"),
      position: widget.eventList[i].trail.markers[0].position,
    ));
  });
}
}

When i check the values, after a clear, markers.lenght = 0, but nothing is removed from the markers in the map. What should I add? A controller?

Thank you in advance!

EDIT I forgot to add, this is Flutter (dart).


Solution

  • You don't need a controller. GoogleMap package has changed in version 0.3.0, markers are widget now and GoogleMap widget takes Set of Markers in it's markers property.

    What you have to do is, have a Set of Markers in your state, give that Set to GoogleMap widget's markers property, and then call setState to mutate this Set.

    This will make the framework schedule a rebuild, so your GoogleMap will be build again with the new set of markers. Check my answer in this post to see code: Adding markers dynamically to flutter google map

    Note: I've posted my comment as an answer, according to this meta post.