等到谷歌地图在MapFragment中有大小

erc*_*can 7 android google-maps google-maps-android-api-2

我的活动在LinearLayout中包含一个MapFragment.我做了以下事情

in onCreate:

  • 我在我的活动的onCreate方法中使用setContentView来扩展此布局.
  • 掌握GoogleMap使用方法getMap().

在onStart上:

  • 我从SQLite数据库中获取了一些位置坐标
  • 将相应的标记添加到地图中
  • 将这些点添加到a LatLngBounds.Builder
  • 使用相机制作动画 newLatLngBounds(Builder.build(), 10)

根据maps api参考,我不应该newLatLngBounds(LatLngBounds bounds, int padding)在确保地图有大小之前打电话.我确实在这一点上得到了IllegalStateException.但是,等到地图有大小的正确方法是什么?

Fer*_*nch 11

rusmus解决方案对我不起作用.我改用了这个:

    map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            map.animateCamera(cameraUpdate);
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果您知道地图大小,则可以避免在显示地图之前等待并移动相机.我们最终使用显示尺寸作为地图尺寸的近似值(但如果您想要更精确,可以找出确切的尺寸):

    final DisplayMetrics display = getResources().getDisplayMetrics();
    final int padding = display.widthPixels / 20;
    final CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(
        boundsBuilder.build(), display.widthPixels, display.heightPixels, padding);
    map.moveCamera(cameraUpdate);
Run Code Online (Sandbox Code Playgroud)


rus*_*mus 8

我过去成功使用了以下代码:

final LatLngBounds.Builder builder = new LatLngBounds.Builder();
final View mapView = fragment.getView();
final GoogleMap map = fragment.getMap():

//Add points to builder. And get bounds...
final LatLngBounds bounds = builder.build();

// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.

if (mapView.getViewTreeObserver().isAlive()) {
    mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        public void onGlobalLayout() {
            mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50), 1500, null);         
        }
    });
}
Run Code Online (Sandbox Code Playgroud)