Reputation:
I have a list of ArrayList of locations pulled from an API, which are added to a GoogleMap generated from a SupportMapFragment.
I create Markers from the list and add them to the map, then add the Marker ids to a Map of marker indexes, to reference later via onInfoWindowClick.
public void addLocationMarkers() {
mGoogleMap.clear();
LocationBlahObject thelocation;
int size = mNearbyLocations.size();
for (int i = 0; i < size; i++) {
thelocation = mNearbyLocations.get(i);
Marker m = mGoogleMap
.addMarker(new MarkerOptions()
.position(
new LatLng(thelocation.Latitude,
thelocation.Longitude))
.title(thelocation.Name)
.snippet(thelocation.Address)
.icon(BitmapDescriptorFactory
.defaultMarker(thelocation.getBGHue())));
mMarkerIndexes.put(m.getId(), i);
}
}
My issue with this, is that sometimes the list of locations can be in the hundreds, and the map will hang for a couple seconds while adding markers.
I have tried using an AsyncTask, but obviously the bulk of the work here is manipulating the UI, and any runOnUiThread or publishProgress shenanigans I do show no difference.
Is there a better way to do this, or a way to create Markers and add them all in bulk that I'm unaware of?
Upvotes: 3
Views: 1499
Reputation: 51
Just came across this from Google. This is how I solved the lag from adding 100+ markers. They slowly pop on, but I think that's OK.
class DisplayPinLocationsTask extends AsyncTask<Void, Void, Void> {
private List<Address> addresses;
public DisplayPinLocationsTask(List<Address> addresses) {
this.addresses = addresses;
}
@Override
protected Void doInBackground(Void... voids) {
for (final Address address : addresses) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
LatLng latLng = new LatLng(address.latitude, address.longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
}
});
// Sleep so we let other UI actions happen in between the markers.
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// Don't care
}
}
return null;
}
}
Upvotes: 3
Reputation: 31
Krypton is right. To avoid lags on UI Thread you must put not very much markers at one time. Put several markers then let UI Thread to do other things then put more markers.
Upvotes: 1