【问题标题】:Waiting until the google map has size in a MapFragment等到谷歌地图在 MapFragment 中有大小
【发布时间】:2014-01-27 14:42:34
【问题描述】:

我的活动在 LinearLayout 中包含一个 MapFragment。我执行以下操作

在 onCreate 中:

  • 我在 onCreate 方法中使用 setContentView 扩展此布局 我的活动。
  • 使用getMap() 获取GoogleMap 的句柄。

在开始时:

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

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

【问题讨论】:

    标签: android google-maps google-maps-android-api-2


    【解决方案1】:

    solution by rusmus 对我不起作用。我改用这个:

        map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                map.animateCamera(cameraUpdate);
            }
        });
    

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

        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);
    

    【讨论】:

    • 这个答案与 rusmus 的答案略有不同。 OnGlobalLayoutListener() 在地图视图布局时调用,而OnMapLoadedCallback() 在所有地图图块加载时调用,即在地图视图布局之后。
    • 正是我想要的!我正在使用 onMapReady 回调,但这个确实可以解决问题
    【解决方案2】:

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

    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);         
            }
        });
    }
    

    【讨论】:

    • 我也是 :-) 我添加了代码以从片段中获取地图视图。
    • 从 API 级别 16 removeGlobalOnLayoutListener 拼写 removeOnGlobalLayoutListener(第一个已弃用)
    【解决方案3】:

    借助最新的 Google 服务,您可以使用 MapFragment.getMapAsync。 直接来自文档

    设置一个回调对象,当 GoogleMap 实例可以使用时触发。

    【讨论】:

    • 可以,通过实现 OnMapReadyCallback 接口及其 onMapReady 回调方法。不幸的是,当调用回调时,可以使用地图,但地图大小可能仍然为零。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2019-09-21
    • 2016-02-25
    相关资源
    最近更新 更多