Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can you call GoogleMap.moveCamera after onMapReady from OnMapReadyCallback?

The current Android Google Maps API requires you call mapFragment.getMapAsync with a OnMapReadyCallback before you can access the GoogleMap. I assumed that once you had the GoogleMap it would then be safe to call moveCamera() but I was seeing crash reports with an IllegalStateException which said Map size can't be 0. Most likely, layout has not yet occured for the map view.

So I tried adding a ViewTreeObserver.OnPreDrawListener, and moving the moveCamera() call to the onPreDraw method, as the docs for that say "At this point, all views in the tree have been measured and given a frame". But I still see some crash reports with the same problem. I can't find any documentation for this — there's questions like moveCamera with CameraUpdateFactory.newLatLngBounds crashes but they pre-date the getMapAsync API, so they're not much help.

like image 647
Jonathan Caryl Avatar asked Jun 19 '15 10:06

Jonathan Caryl


People also ask

When onMapReady is called in Android?

Callback interface for when the map is ready to be used. Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap .


1 Answers

I had the same issue. This google maps library throws the exception when an app try to change the camera with this camera update until the map has undergone layout (in order for this method to correctly determine the appropriate bounding box and zoom level, the map must have a size). It described here.

It's my solution:

@Override
public void onMapReady(GoogleMap googleMap) {
    googleMap.setOnMapLoadedCallback(this);
}

@Override
public void onMapLoaded() {
    googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(…));
}
like image 179
mbelsky Avatar answered Sep 20 '22 13:09

mbelsky