Android: Setting Zoom Level in Google Maps to include all Marker points

Tushar Vengurlekar picture Tushar Vengurlekar · Feb 25, 2011 · Viewed 27.6k times · Source

I am trying to set zoom level for Maps in android such that it includes all the points in my list. I am using following code.

int minLatitude = Integer.MAX_VALUE;
int maxLatitude = Integer.MIN_VALUE;
int minLongitude = Integer.MAX_VALUE;
int maxLongitude = Integer.MIN_VALUE;

// Find the boundaries of the item set
// item contains a list of GeoPoints
for (GeoPoint item : items) { 
    int lat = item.getLatitudeE6();
    int lon = item.getLongitudeE6();

    maxLatitude = Math.max(lat, maxLatitude);
    minLatitude = Math.min(lat, minLatitude);
    maxLongitude = Math.max(lon, maxLongitude);
    minLongitude = Math.min(lon, minLongitude);
}
objMapController.zoomToSpan(
    Math.abs(maxLatitude - minLatitude), 
    Math.abs(maxLongitude - minLongitude));

this works sometimes. However sometimes some points are not shown and I need to then Zoom Out to view those points. Is there any way to solve this problem?

Answer

iutinvg picture iutinvg · Dec 26, 2012

Yet another approach with Android Map API v2:

private void fixZoom() {
    List<LatLng> points = route.getPoints(); // route is instance of PolylineOptions 

    LatLngBounds.Builder bc = new LatLngBounds.Builder();

    for (LatLng item : points) {
        bc.include(item);
    }

    map.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), 50));
}