3

I have checked several questions (this one, this one and this one) concerning zooming the google map to a given Polygon or List<LatLng> in Android, but I haven't been able to find an answer.

What would a function

public static int getZoomLevelForPolygon(final List<LatLng> listOfPolygonCoordinates)

look like? Is there a chance I can zoom the map to a certain polygon?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Simon
  • 2,643
  • 3
  • 40
  • 61

1 Answers1

8

Ok I think I managed to find a solution: First, we generate a minimal rectangle which can fit the polygon, also known as the LatLngBounds object. Then, we move the camera to fit the LatLngBounds provided as an argument.

Main call:

  final int POLYGON_PADDING_PREFERENCE = 200;
  final LatLngBounds latLngBounds = getPolygonLatLngBounds(polygon);
  googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, POLYGON_PADDING_PREFERENCE));

Helper function:

  private static LatLngBounds getPolygonLatLngBounds(final List<LatLng> polygon) {
    final LatLngBounds.Builder centerBuilder = LatLngBounds.builder();
    for (LatLng point : polygon) {
        centerBuilder.include(point);
    }
    return centerBuilder.build();
  }
Simon
  • 2,643
  • 3
  • 40
  • 61
  • 2
    Once you have the LatLngBounds (from your 'getPolygonLatLngBounds') seems like you could just use CameraUpdateFactory.newLatLngBounds. Interestingly though, once you have the CameraUpdate you won't know the zoom level until it is applied. –  Mar 30 '18 at 12:33