Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

android - Remove a marker from a GoogleMap

In the new Google Maps API for Android, we can add a marker, but there is no way to (easily) remove one.

My solution is to keep the markers in a map and redraw the map when I want to remove a marker, but it is not very efficient.

private final Map<String, MarkerOptions> mMarkers = new ConcurrentHashMap<String, MarkerOptions>();

private void add(String name, LatLng ll) {
  final MarkerOptions marker = new MarkerOptions().position(ll).title(name);
  mMarkers.put(name, marker);

  runOnUiThread(new Runnable() {
    @Override
    public void run() {
      mMap.addMarker(marker);
    }
  });
}

private void remove(String name) {
  mMarkers.remove(name);

  runOnUiThread(new Runnable() {
    @Override
    public void run() {
      mMap.clear();

      for (MarkerOptions item : mMarkers.values()) {
        mMap.addMarker(item);
      }
    }
  });
}

Does anyone have a better idea?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The method signature for addMarker is:

public final Marker addMarker (MarkerOptions options)

So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.

As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...