I want to perform fast add/remove or hide/show markers based on a list (the range between firstVisibleItem
and lastVisibleItemsPrevious
.
This is a list that assign from my database on a temporarily on
private List<MarkerOptions> mMarkers = new ArrayList<MarkerOptions>();
private int firstVisibleItemPrevious = 0;
private int lastVisibleItemsPrevious = 0;
//Loops, network commands, etc
// assign a marker per item
MarkerOptions markerOptions = new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.anchor(0.5f, 0.5f)
.visible(false)
.position(new LatLng( (Double) coords.get(1) , (Double) coords.get(0)));
mMarkers.add(position, markerOptions);
And this is how the I/O of the markers is done:
aListView.setOnScrollListener(new OnScrollListener() {
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastVisibleItem = firstVisibleItem+visibleItemCount;
//if we have the markers from the DB and we notice a move do:
if( mMarkers.size() > 0 &&
(firstVisibleItemPrevious != firstVisibleItem ||
lastVisibleItemsPrevious != lastVisibleItem)
){
LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear(); // clear the map to add new markers
for(int x = firstVisibleItem; x < lastVisibleItem; x++){
Marker mMarker = mMap.addMarker(mMarkers.get(x));
builder.include(mMarker.getPosition());
}
//animate
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 60);
mMap.animateCamera(cu);
firstVisibleItemPrevious = firstVisibleItem;
lastVisibleItemsPrevious = lastVisibleItem;
}
}
}
With my method I have three problems:
builder
I tried a method of checking the current visible maps (a list) and check the new list and then add those that are not in the old list and remove those that are not in the new list. However it was still laggy and I ended up adding always markers and not correctly remove the "old" ones. I also tried with Marker.setVisibility()
without success.
What can be a good way to handle these kind of fast operations? Keeping in mind that I should at least have a list of List<MarkerOptions>
or List<LatLng>
or List<Marker>
as my source for the hide/show operation (assigned dynamically).
The bug was in the
mMarkers.add(position, markerOptions);
It was pushing the list.