Issue
I have a MapActivity that is meant to display a specific region, defined by instance variables mCenterPoint, mLatSpan and mLongSpan. The Map object has methods to get the center point, as well as the latitude span and longitude span of the map. When the MapActivity is opened, I want it to immediately center on the center point and zoom to the correct span.
Here is my onCreate method and my setRegionOfMap method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.google_map);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.setBuiltInZoomControls(true);
setRegionOfMap();
}
private void setRegionOfMap(){
mMapView.getController().setCenter(mCenterPoint);
mMapView.getController().zoomToSpan(mLatSpan, mLongSpan);
}
mMap is just an instance of my map object. The center point and spans are always the same value since the data does not change dynamically. About 1/4 - 1/2 of the time the map is zoomed exactly as I expect it to. Yet the rest of the time the map looks centered correctly, except way too far zoomed out. Why would the MapView only zoom some of the time and other times be incorrect? My only theory was that maybe the map isn't totally drawn when the zoomToSpan call occurs, and thus the zoom doesn't register. I haven't been able to test that theory though.
Solution
I ended up solving this on my own by calling zoomToSpan from an OnGlobalLayoutListener. The problem before was that in onCreate(), the map had not been drawn yet, so the zoom had no effect. Calling zoomToSpan from this listener makes sure the map is set up and the zoom has an effect. Here is my "setRegionOfMap()" method.
private void setRegionOfMap(){
final LinearLayout layout = (LinearLayout)findViewById(R.id.outdoor_maps_linearlayout);
final ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
MapView mapView = (MapView)layout.findViewById(R.id.mapview);
mapView.getController().setCenter(mCenterPoint);
mapView.getController().zoomToSpan(mLatSpan, mLongSpan);
}
});
}
Answered By - mattgmg1990
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.