2012-12-18 106 views
2

我正在嘗試在我的Android應用程序中使用Google Maps API v2。我已經使用以下代碼以編程方式添加了地圖片段,然後嘗試從我的SupportMapFragment獲取GoogleMap,但即使地圖顯示在屏幕上,我也總是會返回空結果...任何幫助都會得到高度讚賞!!!!! !從supportmapfragment返回空映射

感謝

public class MapActivity extends BaseFragmentActivity { 


    private SchoolType mSchoolType=SchoolType.ALL; 
    private GoogleMap mMap; 
    private UiSettings mUiSettings; 
    private SupportMapFragment mMapFragment; 
    private static final String MAP_FRAGMENT_TAG = "map"; 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     try{ 
      setContentView(R.layout.map_activity); 
      mMapFragment = (SupportMapFragment) getSupportFragmentManager() 
        .findFragmentByTag(MAP_FRAGMENT_TAG); 
      if(mMapFragment==null) 
       addMapFragment(); 
      setUpMapIfNeeded(); 

     } 
     catch(Exception ex){ 
      System.err.println("Exception: " + ex.getMessage()); 

     } 

    } 

    private void addMapFragment(){ 
     try{ 

      GoogleMapOptions options = new GoogleMapOptions(); 
      options.mapType(GoogleMap.MAP_TYPE_NORMAL) 
        .zoomControlsEnabled(true) ; 

      mMapFragment = SupportMapFragment.newInstance(options); 
      FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
      transaction.add(R.id.fragment_map_content, mMapFragment,MAP_FRAGMENT_TAG); 
      //transaction.addToBackStack(null); 
      transaction.commit(); 
     } 
     catch(Exception ex){ 
      System.err.println("Exception: " + ex.getMessage()); 
     } 

    } 

private void setUpMapIfNeeded() { 
     // Do a null check to confirm that we have not already instantiated the map. 
     if (mMap == null) { 
      // Try to obtain the map from the SupportMapFragment. 
      mMap = mMapFragment.getMap(); ***//ALWAYS RETUN NULL*** 
      //mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 

      // Check if we were successful in obtaining the map. 
      if (mMap != null) { 
       setUpMap(); 
      } 
     } 
    } 
+0

獲取私有GoogleMap mMap;工作,你是否進口任何額外的圖書館或包? – Smoore

回答

0

呼叫的onResume()setUpMapIfNeeded,像這樣。

@Override 
protected void onResume() { 
    super.onResume(); 

    // In case Google Play services has since become available. 
    setUpMapIfNeeded(); 
}