-1

I am populating an array of markers on an Android app, so that I can manipulate them, with a change of icon, etc. if necessary. This is done on the fly, so that the markers are removed from the map, and then deleted. Afterwards the selectedMarkers Array are repopulated afresh based on latitude and longitude etc.

I've defined the following as

    selectedMarkers = new ArrayList<Marker>();

And then I am adding new markers to the list and also to the map in a loop, for example:

      marker = mMap.addMarker(new MarkerOptions().position(new LatLng(fulllat, fulllong)).icon(BitmapDescriptorFactory.fromResource(R.drawable.coffeeshop)));
      marker.setTag( ID_NUM );  // a unique ID
      selectedMarkers.add(marker);

However, I want to delete the selectedMarkers markers and also remove them from the map; I repopulate selectedMarkers with new data every so often.

A niggle is that my googleMap has other markers on it that I don't want touched, so I can't call googleMap.clear() as this would remove everything. How can I delete the selectedMarkers and also purge them from the map, leaving the other stuff untouched? Looking at the SDK documentation, marker.remove() might do the trick but I'm not clear if the marker itself is vapourised too. I've tried selectedMarkers.clear() but this just wipes the array leaving the markers remaining on the map.

Many thanks for your help

2
  • 2
    Have you tried to loop on selectedMarkers and use marker.remove() in iteration block. Don't forget to use selectedMarkers.clear() after loop code. Commented May 25 at 22:34
  • Thank you Adnan. Do I need to worry about the GC picking up on the removed markers? Commented May 28 at 21:21

1 Answer 1

0

I would suggest defining selectedMarkers in a different way.

A couple of different approaches:

For example, selectedMarkers = mutableStateListOf<YourMarkerData>() (If defined in a ViewModel -- you are using a ViewModel, right? 🙂 ) or selectedMarkers by remember { mutableStateListOf<YourMarkerData>() }

Better, would be to use flows and a filter. For example, this code filters a list of markers down to the set to display in the map.

Consider trying the codelab if you have not already done so.

Not the answer you're looking for? Browse other questions tagged or ask your own question.