You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何通过Marker ID移除Google Maps特定标记(最新插件版)

Fixing Marker Removal with Latest google_maps_flutter Plugin

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:

  1. First, define a fixed MarkerId in your State class (so it stays consistent across location updates):
final MarkerId _liveOrderMarkerId = MarkerId("live_order_location");
Set<Marker> _markers = {};
  1. Update your showLiveLocation method 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(() {});
}
  1. Make sure your GoogleMap widget is linked to the _markers set:
GoogleMap(
  initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 15),
  markers: _markers, // Connect your marker set here
  // Other map properties...
)

Why This Works

  • The fixed MarkerId lets you reliably locate and remove the old marker every time the location updates.
  • Since Marker objects are compared using their markerId, the removeWhere method will accurately target the old marker.
  • Calling setState ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 21:18:14