I build an app which use GMaps with several markers. The user can add or delete markers but my problem is to select the good zoom level to display all the markers.
That zoom level can change if the user add or delete markers.
For centering the camera I use the following code :
double xMin = 90.0 ;
double xMax = 0.0 ;
double yMin = 90.0 ;
double yMax = 0.0 ;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Place place : places) {
if (place.getLatitude() < xMin)
xMin = place.getLatitude();
if (place.getLatitude() > xMax)
xMax = place.getLatitude();
if (place.getLongitude() < yMin)
yMin = place.getLongitude();
if (place.getLongitude() > yMax)
yMax = place.getLongitude();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(place.getLatitude(), place.getLongitude()));
markerOptions.title(String.valueOf(place.getId()));
Marker marker = this.googleMap.addMarker(markerOptions);
allMarkersMap.put(marker, place);
displayMarkersMap.put(marker, place);
builder.include(marker.getPosition());
}
double xPos = (xMax + xMin) / 2;
double yPos = (yMax + yMin) / 2;
LatLngBounds bounds = builder.build();
int padding = 1; // offset from edges of the map in pixels
//CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
//this.googleMap.moveCamera(cameraUpdate);
LatLng latLng = new LatLng(xPos, yPos);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(2).build();
this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
But I don't find a solution to have a good zoom value.