2013-01-22 20 views
7

我對使用新Google Maps API嵌入SuportMapFragment的片段存在問題。當我的片段被創建時,它會從onResume方法開始獲取AsyncTask中的一些數據。發生這種情況時,MapFragment保持不在屏幕上,而是顯示一個進度條。爲什麼GoogleMap.animateCamera()會在onGlobalLayout()之後崩潰?

AsyncTask完成時,我註冊了mapView的onGlobalLayout事件。然後我顯示片段,導致地圖視圖顯示和佈局。 onGlobalLayout被觸發並且動畫開始。

這工作得很好很長一段時間,直到我開始在數據收集AsyncTask優化操作幾乎在瞬間完成。現在,應用程序在啓動時通常會崩潰,更常見的是Release和Debug,這就是爲什麼我認爲我正在處理一個我不知道的賽車條件。

異常寫着:

地圖的大小不應該是0。最有可能的,佈局尚未發生的地圖視圖。

任何見解是不勝感激。

供參考:這是一個似乎會導致崩潰的代碼:

// Hide status UI 
this.progressBar.setVisibility(View.INVISIBLE); 
this.statusTextView.setVisibility(View.INVISIBLE); 

// Update state 
this.uraDataDownloadFinished = true; 

// Schedule map translation to occur when layout is complete 
final View mapView = this.mapFragment.getView(); 
if (mapView.getViewTreeObserver().isAlive()) 
{ 
    mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
    { 
     @SuppressWarnings("deprecation") 
     @SuppressLint("NewApi") // We check which build version we are using. 
     @Override 
     public void onGlobalLayout() 
     { 
      Log.d(TAG, "onGlobalLayout()"); 
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) 
      { 
       mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      } 
      else 
      { 
       mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
      } 

      // here we crash 
      this.map.animateCamera(
        CameraUpdateFactory.newLatLngBounds(
          LatLngBounds.builder() 
           .include(topLeft) 
           .include(topRight) 
           .include(bottomLeft) 
           .include(bottomRight) 
           .build(), 
          0), 
        durationMs, 
        null); 
     } 
    }); 
} 

// Show map (which will eventually trigger onGlobalLayout) 
this.getFragmentManager().beginTransaction().show(this.mapFragment).commit(); 
this.mapFragment.getMap().setOnCameraChangeListener(this); 

非常感謝!

回答

5

我不知道,但是,你正在使用的AsyncTask可能是你正在試圖獲得地圖邊界地圖已經佈局發生之前。

你可以看到documentation,它建議使用newLatLngBounds(boundary, width, height, padding)代替。

+0

謝謝,這工作。由於地圖完全填充佈局容器,因此可以使用其尺寸。但是,我的問題依然存在。由於我在等待'onGlobalLayout()',我不應該遇到這個問題,我應該嗎? – Chris

+0

不,我不這麼認爲,你必須等地圖經過佈局。 – jgonza73

+0

...或沒有地圖編輯CameraOptions界定 – jgonza73

3

試試這個,它爲我工作:

map.setOnCameraChangeListener(new OnCameraChangeListener() { 

    @Override 
    public void onCameraChange(CameraPosition arg0) { 
     // Move camera. 
     map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 10)); 
     // Remove listener to prevent position reset on camera move. 
     map.setOnCameraChangeListener(null); 
    } 
});