Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps API v2 newLatLngBounds using percentage padding throws error in Multi-Window mode

I am animating the camera to a LatLngBounds with a padding set based on the percentage of the device width so that it works on small devices.

This works even on small devices with 4inch displays, however it fails in multi-window mode in Android 7.0 and devices that support multi-window mode before that, eg. Galaxy S7.

I get the following exception on devices in multi-window mode:

Fatal Exception: java.lang.IllegalStateException: Error using newLatLngBounds(LatLngBounds, int, int, int): View size is too small after padding is applied.

Here is the suspect code:

private void animateCamera() {

    // ...

    // Create bounds from positions
    LatLngBounds bounds = latLngBounds(positions);

    // Setup camera movement
    final int width = getResources().getDisplayMetrics().widthPixels;
    final int height = getResources().getDisplayMetrics().heightPixels;
    final int padding = (int) (width * 0.40); // offset from edges of the map in pixels
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

    mMap.animateCamera(cu);
}

How can I properly set the padding in newLatLngBounds to work on all device widths and in multi-window mode?

like image 498
Ryan R Avatar asked Feb 05 '23 20:02

Ryan R


1 Answers

The solution is to choose the minimum metric between width and height, since in Multi-window mode the height can be smaller than the width:

private void animateCamera() {

    // ...

    // Create bounds from positions
    LatLngBounds bounds = latLngBounds(positions);

    // Setup camera movement
    final int width = getResources().getDisplayMetrics().widthPixels;
    final int height = getResources().getDisplayMetrics().heightPixels;
    final int minMetric = Math.min(width, height);
    final int padding = (int) (minMetric * 0.40); // offset from edges of the map in pixels
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

    mMap.animateCamera(cu);
}
like image 84
Ryan R Avatar answered Feb 10 '23 00:02

Ryan R