Israel Varea
Israel Varea

Reputation: 2630

GoogleMaps v2 for Android: Cannot remove marker while map is being rendered

I have a fragment with:

When user clicks on "places" button, the app stores a hashmap with references to markers and places object in a WeakHashMap. When user clicks "remove places" the app iterates over the map keys calling marker.remove().

When the map is completely rendered, the markers are removed properly, but, if the button is pressed while map is being rendered, then the markers are not removed.

Anyone has experienced the same problem? How to solve it?

I cannot use map.clear() since it removes all markers, polylines, overlays, etc. I just want to remove a previously stored list of markers (user's places) not everything.

Upvotes: 3

Views: 845

Answers (3)

Israel Varea
Israel Varea

Reputation: 2630

The problem was that the object to store the relation between the Marker and the Place object shouldn't be a WeakHashMap but a HashMap. It solved the problem.

Upvotes: 1

Simas
Simas

Reputation: 44118

You can use a few booleans to check if the map has finished loading. If not delay the removing of the markers until it is. Here's an example:

private boolean mLoadFinished, mDelayRemove;

public void removeMarkers() {
    for (Marker marker : markers) {
        marker.remove();
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    Button button;
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mLoadFinished) {
                mDelayRemove = true;
            } else {
                removeMarkers();
            }
        }
    });

    mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            mLoadFinished = true;
            if (mDelayRemove) {
                mDelayRemove = false;
                removeMarkers();
            }
        }
    });

    ...
}

Upvotes: 3

Hasnain
Hasnain

Reputation: 272

GoogleMAp.clear() will remove all the marker you plotted on the map

Upvotes: 1

Related Questions