Keep Map Target While Zooming To Show All Markers
13 Dec 2014
Recently an app I develop needed to keep the map center while zooming in/out to show all markers dropped on the map. It’s not a particularly difficult thing to do, but it took a moments thought. The example is for Android, but it works the same way on iOS etc.
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
LatLng currentLoc = _googleMapView.getCameraPosition().target;
//make sure that centre location doesn't change
double deltaLat = Math.max(Math.abs(bounds.southwest.latitude - currentLoc.latitude),
Math.abs(bounds.northeast.latitude - currentLoc.latitude));
double deltaLon = Math.max(Math.abs(bounds.southwest.longitude - currentLoc.longitude),
Math.abs(bounds.northeast.longitude - currentLoc.longitude));
LatLngBounds.Builder displayBuilder = new LatLngBounds.Builder();
displayBuilder.include(currentLoc); //not necessary but hey
displayBuilder.include(new LatLng(currentLoc.latitude + deltaLat, currentLoc.longitude + deltaLon));
displayBuilder.include(new LatLng(currentLoc.latitude - deltaLat, currentLoc.longitude - deltaLon));
_googleMapView.moveCamera(CameraUpdateFactory.newLatLngBounds(displayBuilder.build(), 0));