Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a specific marker from google maps in flutter?

Tags:

flutter

I am Vaibhav Pathak. I am working on a Flutter app in which I add markers in-app based on data change in firestore database and I want to remove the previous marker from the map using its marker id but I don't understand how to do it. I had watched many Youtube videos and blogs but I don't get to know this because of API changes in google maps flutter plugin. For your kind information, I want to tell that I am using the latest version of the google_maps flutter plugin.

My Code for Making Markers :

showLiveLocation(LatLng latLng) {
_markers.add(
  Marker(
    markerId: MarkerId(latLng.toString()),
    position: latLng,
    draggable: false,
    infoWindow: InfoWindow(
        title: "Live Order Location",
        snippet: "Dear customer your order is live at this place."),
    icon: liveLocation,
    visible: true,
  ),
);

}

Thanks for everyone's help.

github : github@vkpdeveloper

like image 354
Vaibhav Pathak Avatar asked Oct 21 '25 16:10

Vaibhav Pathak


2 Answers

You need to find that specific marker in your _markers list (e.g. by firstWhere()) and then remove it from the list of markers.

Edit:

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

This will trigger a rebuild of your map where the marker is no longer included.

like image 61
Thomas Avatar answered Oct 23 '25 08:10

Thomas


Inspired by Thomas, my solution was:

setState(() {
  _markers.removeWhere((key, marker) => marker.markerId.value == "myMarkerId");
});
like image 41
Bo Kristensen Avatar answered Oct 23 '25 08:10

Bo Kristensen