Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a fragment with:

  • GoogleMap v2 fragment
  • A "places" button to add markers (user's places)
  • A "remove places" button (remove user generated markers)
  • Additional markers (such as general point of interests)
  • Custom tile overlay

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.

like image 348
Israel Varea Avatar asked Mar 08 '26 20:03

Israel Varea


2 Answers

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

    ...
}
like image 77
Simas Avatar answered Mar 10 '26 09:03

Simas


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

like image 32
Hasnain Avatar answered Mar 10 '26 08:03

Hasnain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!