Flutter中如何通过Marker ID移除Google Maps特定标记(最新插件版)
Hey Vaibhav, I get your frustration—recent API updates for the google_maps_flutter plugin changed how marker management works, but we can sort this out with a simple tweak to your code.
The Core Issue in Your Current Code
Right now, you’re using latLng.toString() as your MarkerId. Every time the location updates, this ID changes, which means you can’t target the old marker to remove it. Instead, you just keep adding new markers to the map, leaving old ones stuck around.
The Solution: Use a Fixed Marker ID
Here’s how to adjust your code to properly remove the old marker before adding a new one:
- First, define a fixed
MarkerIdin your State class (so it stays consistent across location updates):
final MarkerId _liveOrderMarkerId = MarkerId("live_order_location"); Set<Marker> _markers = {};
- Update your
showLiveLocationmethod to first remove the old marker (using the fixed ID) and then add the new one:
void showLiveLocation(LatLng latLng) { // Remove the existing live marker if it exists _markers.removeWhere((marker) => marker.markerId == _liveOrderMarkerId); // Add the new live marker with the same fixed ID _markers.add( Marker( markerId: _liveOrderMarkerId, // Reuse the fixed ID here position: latLng, draggable: false, infoWindow: const InfoWindow( title: "Live Order Location", snippet: "Dear customer your order is live at this place."), icon: liveLocation, visible: true, ), ); // Trigger a UI update to refresh the map markers setState(() {}); }
- Make sure your
GoogleMapwidget is linked to the_markersset:
GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 15), markers: _markers, // Connect your marker set here // Other map properties... )
Why This Works
- The fixed
MarkerIdlets you reliably locate and remove the old marker every time the location updates. - Since
Markerobjects are compared using theirmarkerId, theremoveWheremethod will accurately target the old marker. - Calling
setStateensures the map widget refreshes to display only the latest marker.
Now, whenever your Firestore data updates and you call showLiveLocation, the old marker will be removed automatically before the new one is added—no more leftover markers cluttering your map!
内容的提问来源于stack exchange,提问作者Vaibhav Pathak

