Waiting until the google map has size in a MapFragment
android, google-maps, google-maps-android-api-2
Solution
I have succesfully used the following code in the past:
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
final View mapView = fragment.getView();
final GoogleMap map = fragment.getMap():
//Add points to builder. And get bounds...
final LatLngBounds bounds = builder.build();
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50), 1500, null);
}
});
}
Problem
My activity contains a MapFragment in a LinearLayout. I do the following in onCreate: - I inflate this layout using setContentView in the onCreate method of my activity. - Get a handle to the `GoogleMap` using `getMap()`. in onStart: - I get some place coordinates from an SQLite Database - add corresponding markers to the map - add these points to a `LatLngBounds.Builder` - animate the camera using `newLatLngBounds(Builder.build(), 10)` According to maps api reference, I shouldn't call `newLatLngBounds(LatLngBounds bounds, int padding)` before making sure that the map has a size. I indeed get an IllegalStateException at this point. But what is the right method for waiting until the map has a size?