I have a list of random latitude and longitude points and I am drawing a route between them. My question is how to bound this route within google map I made below utili
I implemented a similar solution to @rishabh-dutt-sharma with a couple of twists:
This is the code (adapted from my original code, I hope there are no typos):
public void zoomRoute(GoogleMap googleMap, List lstLatLngRoute) {
if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return;
LatLngBounds currentLatLongBounds =
googleMap.getProjection().getVisibleRegion().latLngBounds;
boolean updateBounds = false;
for (LatLng latLng : lstLatLngRoute) {
if (!currentLatLongBounds.contains(latLng)) {
updateBounds = true;
}
}
if (updateBounds) {
CameraUpdate cameraUpdate;
if (lstLatLngRoute.size() == 1) {
LatLng latLng = lstLatLngRoute.iterator().next();
cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
} else {
LatLngBounds.Builder builder = LatLngBounds.builder();
for (LatLng latLng : lstLatLngRoute) {
builder.include(latLng);
}
LatLngBounds latLongBounds = builder.build();
cameraUpdate =
CameraUpdateFactory.newLatLngBounds(latLongBounds, MAP_ZOOM_PADDING);
}
try {
googleMap.animateCamera(cameraUpdate, MAP_CAMERA_ANIMATION_DURATION_IN_MILLIS,
new GoogleMap.CancelableCallback() {
@Override
public void onFinish() {
}
@Override
public void onCancel() {
}
});
} catch (IllegalStateException ex) {
// Ignore it. We're just being a bit lazy, as this exception only happens if
// we try to animate the camera before the map has a size
}
}
}