You can override onMarkerClick
like below
@Override
public boolean onMarkerClick(Marker marker) {
if (markerClicked) {
if (polygon != null) {
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(ContextCompat.getColor(getContext(), R.color.colorRedTransparent));
polygonOptions.fillColor(ContextCompat.getColor(getContext(), R.color.colorBlueTransparent));
polygonOptions.strokeWidth(5.0f);
polygon = mMap.addPolygon(polygonOptions);
polygon.setClickable(true);
} else {
if (polygon != null) {
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
}
return true;
}
Pass your polygon to generate bounding box
public static Rectangle getBoundingBox(Polygon polygon) {
double boundsMinX = Double.MAX_VALUE; // bottom south latitude of the bounding box.
double boundsMaxX = Double.MIN_VALUE; // top north latitude of bounding box.
double boundsMinY = Double.MAX_VALUE; // left longitude of bounding box (western bound).
double boundsMaxY = Double.MIN_VALUE; // right longitude of bounding box (eastern bound).
for (int i = 0; i < polygon.getPoints().size(); i++) {
double x = polygon.getPoints().get(i).latitude;
boundsMinX = Math.min(boundsMinX, x);
boundsMaxX = Math.max(boundsMaxX, x);
double y = polygon.getPoints().get(i).longitude;
boundsMinY = Math.min(boundsMinY, y);
boundsMaxY = Math.max(boundsMaxY, y);
}
//Rectangle(double left, double bottom, double right, double top)
return new Rectangle(boundsMinY, boundsMinX, boundsMaxY, boundsMaxX);
}