如何从地图中删除标记

时间:2017-01-05 13:33:36

标签: android google-maps

我使用谷歌地图创建片段。 但是当我想从地图上删除标记时,我不能这样做。我尝试了一切,没有任何帮助我。标记中继删除但仍在地图上显示我的代码中的错误是什么?

MapFragment.java

HashMap<String, BaseMarker> mAllMarkers = new HashMap<>();
private GoogleMap mMap;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
try {
        mRoot = inflater.inflate(R.layout.fragment_map, null);
    } catch (InflateException e) {

    /* map is already there, just return view as it is */
    }


    mMap = null;
    mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
            .getMap();

  for (final BaseMarker entry : baseMarkers) {//list of markers
    Marker marker =  mMap.addMarker(markerFactory.getMeetingPointCreateMarker(getActivity(),  (MeetingPoint) entry));
                    marker.showInfoWindow();
                    entry.setMarker(marker);
                    mAllMarkers.put(entry.getMarkerId(), entry);
  }
  mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
         public boolean onMarkerClick(final Marker marker) {
           removeMarker();
          }
  });

    return mRoot;
}



public removeMarker(){//this call when I click in marker
 for (Map.Entry<String, BaseMarker> entry : mAllMarkers.entrySet()) {
        BaseMarker marker = entry.getValue();
        if (marker.getMarker() != null) { 
                marker.getMarker().remove();
                mAllMarkers.remove(marker.getMarkerId());

          }
    }

}

我的mapFragment.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical">

  <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/mapFooter">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

  </RelativeLayout>

2 个答案:

答案 0 :(得分:0)

添加后,您将立即删除所有标记。当视图甚至没有完全加载时,您正在执行此操作。

答案 1 :(得分:0)

有一种更简单的方法,只需像这样调用marker.remove()

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.remove();
        return false;
    }
});

此外,还需要调用marker.setVisible(false)来阻止它重新出现。