【问题标题】:Remove marker in google_maps_flutter删除 google_maps_flutter 中的标记
【发布时间】:2019-04-07 12:17:14
【问题描述】:

我已添加Google Maps for Flutter 我知道如何添加标记,因为它在示例中明确给出

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);

我正在删除如下标记

googleMapController.removeMarker(marker);

对于添加标记,它将 MarkerOptions 对象作为参数,但对于删除标记,它要求 Marker 对象作为参数,并且我的删除标记代码不起作用。 我收到以下错误

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

【问题讨论】:

  • 能否分享您用于删除的所有错误行和整个代码块?你能确定那个标记在那一刻不为空吗?因为在这个例子中,它看起来很简单github.com/flutter/plugins/blob/…
  • 尝试这个googleMapController.removeMarker(marker);时出现同样的错误

标签: google-maps flutter google-maps-markers


【解决方案1】:

有两种方法,一种是通过clearMarkers()方法

mapController.clearMarkers();

另一种是通过定位mapController.markers返回的每个标记

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

【讨论】:

  • v2中没有这种方法
【解决方案2】:

使用clearMarkers()。它将清除地图中的所有标记。所以试试googleMapController.clearMarkers();

【讨论】:

    【解决方案3】:

    2020 年答案:

    .clearMarkers() 已被弃用,因为现在每个标记都是存储在地图中的小部件。现在清除 Google Map 上所有标记的正确方法是将标记 Map 的状态设置为空地图。

    例如

                    ...
                      onPressed: () {
                        setState(() {
                          gMapMarkers = {};
                        });
                      }
                    ....
    

    【讨论】:

      【解决方案4】:

      我自己在google_maps_library 上遇到过这个问题,这个问题'_markers[marker._id] == marker': is not true. 的主要原因是所有GoogleMapsController 方法都返回Future,所以这个错误是,假设是并发问题,因为方法 cals 是async

      添加/删除标记的正确方法是:

      _testRemoveMarker() async {
          Marker marker = await _mapController.addMarker(...markerOption..);
          _mapController.removeMarker(marker);
      } 
      
      _clearMarkersAndRead() async {
         _mapController.clearMarkers().then((_) {
             //TODO: add makrers as you whish;
         });
      }
      

      因此,如果您对标记添加/删除/更新进行任何操作,您应该确保之前涉及标记的操作已完成。

      【讨论】:

        猜你喜欢
        • 2020-02-14
        • 2020-01-15
        • 2019-06-04
        • 2021-07-04
        • 1970-01-01
        • 2020-10-18
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多