Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How update markers on Map when using ClusterManager

I am trying to update my map with newer data from server but I can't figure out how to remove old items (markers and cluster - Using ClusterManager) from map ( - seems to me that I can only add in ClusterManager.

I have BroadcastReceiver which get intent when there are new data. I was trying something like this: ( but it gives me UnsupportedOperationException on line with "...getMarkers().clear();"

private BroadcastReceiver myRefrestMapBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive");
        mClusterManager.clearItems();
        mClusterManager.getMarkerCollection().getMarkers().clear();
        mClusterManager.getClusterMarkerCollection().getMarkers().clear();
        mClusterManager.addItems(LocationGetter.getReports());
    }
};

I added data to map only with this function.

java.util.Collection<Marker> userCollection = mClusterManager.getMarkerCollection().getMarkers();
            ArrayList<Marker> userList = new ArrayList<Marker>(userCollection);
            // now is userList empty
            for(Marker marker: userList){
                marker.remove();
            }

            java.util.Collection<Marker> userCollection2 = mClusterManager.getClusterMarkerCollection().getMarkers();
            ArrayList<Marker> userList2 = new ArrayList<Marker>(userCollection2);
            // now is userList2 empty
            for(Marker marker: userList2){
                marker.remove();
            }

            mClusterManager.addItems(LocationGetter.getReports());
like image 788
United121 Avatar asked Sep 22 '15 21:09

United121


2 Answers

You should be able to do:

val didUpdate = clusterManager?.updateItem(MyClusterItem(data))
clusterManager?.cluster()

The key here to ensure that the clusterManager does actually update the item is to override equals and hashcode in your class that extends ClusterItem, like:

fun getId(): String {
    return data.id
}
override fun equals(other: Any?): Boolean {
    return other is MyClusterItem && other.getId() == getId()
}
override fun hashCode(): Int {
    return getId().hashCode()
}
like image 114
hitch45 Avatar answered Sep 19 '22 08:09

hitch45


I was concentrating the whole time on ClusterManager, so I forgot about GoogleMap, and specifically the method clear(). I was able to solve the problem with this code:

mGoogleMap.clear();
mClusterManager.clearItems();  // calling just in case (may not be needed)
mClusterManager.addItems(LocationGetter.getReports());
like image 35
United121 Avatar answered Sep 18 '22 08:09

United121