Simon
Simon

Reputation: 2733

Google Maps - zoom to polygon

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?

Upvotes: 3

Views: 2581

Answers (1)

Simon
Simon

Reputation: 2733

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();
  }

Upvotes: 8

Related Questions