在片段中使用Google Map v2的推荐方法是什么?

时间:2013-03-05 14:16:57

标签: android android-mapview android-maps android-maps-v2

我想在片段中添加自定义布局的地图。

  1. 我可以使用添加SupportMapFragment的ChildFragmentManager来实现。这种方法目前正在使用。但它有缺点,因为子片段事务是异步的,很难保证getMap不会返回null。
  2. 另一种方法是从超级onCreateView

    mapView = super.onCreateView(inflater, container, savedInstanceState);

    扩展SupportMapFragment商店mapView,并将其插入到膨胀的布局中。主要问题是,然后片段尝试从保存状态恢复谷歌地图SDK内部粉碎。

  3. 还有其他方法可以解决这个问题。如果谷歌地图团队的某个人会推荐正确的方法会很好,因为你没有在样本中加入这样的东西。

2 个答案:

答案 0 :(得分:13)

所有FragmentTransaction都是异步的。如果您希望您的交易立即发生,您必须像以下一样强制执行:

getChildFragmentManager().beginTransaction.add(R.id.container, new MyMapFragment(), "MyMapFragment").commit();
getChildFragmentManager().executePendingTransactions();
/* getMap() should not return null here */

来自Android Developer Site

  

在使用FragmentTransaction提交FragmentTransaction.commit()之后,计划在进程的主线程上异步执行它。如果要立即执行任何此类挂起操作,可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意调用它的位置。

     

<强>返回
  如果有任何待执行的事务要执行,则返回true。

答案 1 :(得分:3)

您可以在片段(或活动)中使用MapView,这样您就可以使用您想要的任何布局。

即。您的布局可能如下所示:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.google.android.gms.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

您还需要将Fragment的生命周期方法(如onCreate,onResume等)转发到MapView。

唯一的区别(似乎是Google地图中的错误?)是您还需要手动初始化Google地图:

private void setUpMapIfNeeded() {
    if (mMap == null) {
        mMap = mMapView.getMap();
        if (mMap != null) {
            // Thought official docs says that it is not necessary to call
            // initialize() method if we got not-null GoogleMap instance from
            // getMap() method it seems to be wrong in case of MapView class.
            try {
                MapsInitializer.initialize(getActivity());
                setUpMap(mMap);
            } catch (GooglePlayServicesNotAvailableException impossible) {
                mMap = null;
            }
        }
    }
}