Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

animateCamera works and moveCamera doesn't for GoogleMap - Android

I need to move Camera to cover all Markers on it. So, I build LatLngBounds and then try to call mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 15)). Problem is when I use moveCamera() method, I'm getting IllegalStateException, but when I use animateCamera() it goes just fine. I call both methods in onMapReady callback. What is going on?

My stacktrace (main part):

java.lang.IllegalStateException: Error using newLatLngBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view.  Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions.

How is it possible that one method knows map size and the other one not?

like image 666
Aleksandar Avatar asked Jan 20 '26 05:01

Aleksandar


1 Answers

As per documentation , this API can't be used before the map has undergone layout. It says

Note: Only use the simpler method newLatLngBounds(boundary, padding) to generate a CameraUpdate if it is going to be used to move the camera after the map has undergone layout. During layout, the API calculates the display boundaries of the map which are needed to correctly project the bounding box. In comparison, you can use the CameraUpdate returned by the more complex method newLatLngBounds(boundary, width, height, padding) at any time, even before the map has undergone layout, because the API calculates the display boundaries from the arguments that you pass.

But you can make use of newLatLngBounds() method in OnCameraChangeListener. Everything will work perfectly and you don't need to calculate screen size. As far as I know, this event occurs after map size calculation.

    mMap.setOnCameraChangeListener(new OnCameraChangeListener() {

    @Override
    public void onCameraChange(CameraPosition arg0) {
        // Move camera.
        mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 15));
        // Remove listener to prevent position reset on camera move.
        mMap.setOnCameraChangeListener(null);
    }
});
like image 181
Mukesh Rana Avatar answered Jan 22 '26 19:01

Mukesh Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!