Here's some code i pieced together to create a new MapView method named fitToBoundingBox:
public synchronized void fitToBoundingBox(final BoundingBox pBoundingBox, final int pMaximumZoom) {
int width = this.getWidth();
int height = this.getHeight();
if (width <= 0 || height <= 0) {
this.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
MapView.this.getViewTreeObserver().removeGlobalOnLayoutListener(this);
fitToBoundingBox(pBoundingBox, pMaximumZoom);
}
});
} else {
Projection projection1 = this.getProjection();
GeoPoint pointSouthWest = new GeoPoint(pBoundingBox.minLatitude, pBoundingBox.minLongitude);
GeoPoint pointNorthEast = new GeoPoint(pBoundingBox.maxLatitude, pBoundingBox.maxLongitude);
Point pointSW = new Point();
Point pointNE = new Point();
byte maxLvl = (byte) Math.min(pMaximumZoom, this.getMapZoomControls().getZoomLevelMax());
byte zoomLevel = 0;
while (zoomLevel < maxLvl) {
byte tmpZoomLevel = (byte) (zoomLevel + 1);
projection1.toPoint(pointSouthWest, pointSW, tmpZoomLevel);
projection1.toPoint(pointNorthEast, pointNE, tmpZoomLevel);
if (pointNE.x - pointSW.x > width) {
break;
}
if (pointSW.y - pointNE.y > height) {
break;
}
zoomLevel = tmpZoomLevel;
}
this.getMapViewPosition().setMapPosition(new MapPosition(pBoundingBox.getCenterPoint(), zoomLevel));
}
}
The check for width and height being zero is optional - the MapView has no layout when initially created/added to your Activity so this code waits until it has layout.
You could omit that if not required.
This method works on MapsForge version 0.3.1, if you're using an older version you'll need to modify it slighty for the different syntax in your version.
Martin.