Remove marker in google_maps_flutter

妖精的绣舞 提交于 2019-12-08 02:02:04

问题


I have added Google Maps for Flutter i know how to add a marker as it is given clearly in there examples

MarkerOptions _options = new MarkerOptions(
          position: LatLng(
            driver_lat,
            driver_lng,
          ),
          infoWindowText:
              const InfoWindowText('An interesting location', '*'));

      Marker marker = new Marker('1', _options);

      //Adding Marker
      googleMapController.addMarker(_options);

And i am removing the marker like below

googleMapController.removeMarker(marker);

for adding the marker it is taking MarkerOptions object as a parameter but for removing the marker it is asking for Marker object as parameter and my removing marker code is not working. i am getting the below error

Failed assertion: line 201 pos 12: '_markers[marker._id] == marker': is not true.

回答1:


Use clearMarkers(). It will clear all markers in your map. So try googleMapController.clearMarkers();




回答2:


There are two ways to do this, one is via clearMarkers() Method

mapController.clearMarkers();

Another one is via targeting each marker returned by mapController.markers

mapController.markers.forEach((marker){
      mapController.removeMarker(marker);
});



回答3:


I've came across this issue myself with the google_maps_library and the main cause of this issue '_markers[marker._id] == marker': is not true. is the fact that all GoogleMapsController methods return a Future, so this error is, let's say a concurrency issue since the method cals are async.

The correct way to add/remove a marker would be:

_testRemoveMarker() async {
    Marker marker = await _mapController.addMarker(...markerOption..);
    _mapController.removeMarker(marker);
} 

_clearMarkersAndRead() async {
   _mapController.clearMarkers().then((_) {
       //TODO: add makrers as you whish;
   });
}

So, if you do any operations with the markers add/remove/update, you should be sure that the previous operation that involved markers is completed.



来源:https://stackoverflow.com/questions/53132358/remove-marker-in-google-maps-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!