初始化MapFragment编程方式与地图API V2 [英] Initialize MapFragment programmatically with Maps API v2

查看:139
本文介绍了初始化MapFragment编程方式与地图API V2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个MapFragment添加到我的当前片段。使用嵌套的片段仅限于FragmentTransactions,您不能使用XML标记的布局。 另外,我希望它被加入到主片段,当用户presses一个按钮。所以,我创建了MapFragment编程与的getInstance()当用户presses的按钮,将它添加到适当的位置。这是正确显示,到目前为止,一切顺利。

问题是,附着MapFragment后,我需要得到一个引用 GoogleMap的 放置标记,但的GetMap()方法返回null(该片段的 onCreateView()还没有叫过)。

我看着演示的例子code,我发现他们使用的初始化MapFragment在的onCreate()和获得提及的GoogleMap的<

解决方案

C $ C> onResume(),在 onCreateView()被调用。

我需要参考的MapFragment初始化后立即使用GoogleMap,因为我希望用户能够显示或隐藏一个按钮地图。我知道,一个可能的解决方案是创建地图在开始如上所说,只是将它的知名度了,但我希望地图默认为关闭,因此它不占用用户的带宽,如果他们没有明确要求吧。

我试图与 MapsInitializer ,但也不管用。我有点卡住。有任何想法吗? 下面是我的测试code到目前为止:

 公共类ParadaInfoFragment扩展BaseDBFragment {
// BaseDBFragment仅仅是一个定制的实用方法SherlockFragment。

私有静态最后弦乐MAP_FRAGMENT_TAG =地图;
私人GoogleMap的MMAP;
私人SupportMapFragment mMapFragment;
私人TextView的mToggleMapa;
私人布尔isMapVisible = FALSE;

@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
    视图V = inflater.inflate(R.layout.fragment_parada_info,集装箱,假);
    mToggleMapa =(TextView中)v.findViewById(R.id.parada_info_map_button);
    返回伏;
}

@覆盖
公共无效的OnStart(){
    super.onStart();
    mToggleMapa.​​setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            如果(!isMapVisible){
                openMap();
            } 其他 {
                closeMap();
            }
            isMapVisible = isMapVisible!;
        }
    });
}

私人无效openMap(){
    //创建初始配置供图
    GoogleMapOptions选项=新GoogleMapOptions()。相机(CameraPosition.fromLatLngZoom(新经纬度(37.4005502611301,-5.98233461380005),16))
            .compassEnabled(false).mapType(GoogleMap.MAP_TYPE_NORMAL).rotateGesturesEnabled(false).scrollGesturesEnabled(false).tiltGesturesEnabled(false)
            .zoomControlsEnabled(假).zoomGesturesEnabled(假);

    //从样品code修改:
    //这是不可能以编程方式设置一个片段的id,所以我们设置了
    //标记,而不是和搜索它使用。
    mMapFragment =(SupportMapFragment)getChildFragmentManager()findFragmentByTag(MAP_FRAGMENT_TAG)。

    //我们只创建一个片段,如果它不存在。
    如果(mMapFragment == NULL){
        //以编程方式添加地图,我们先创建一个
        // SupportMapFragment。
        mMapFragment = SupportMapFragment.newInstance(选件);
        //然后用FragmentTransaction我们添加。
        FragmentTransaction fragmentTransaction = getChildFragmentManager()的BeginTransaction()。
        fragmentTransaction.add(R.id.parada_info_map_container,mMapFragment,MAP_FRAGMENT_TAG);
        fragmentTransaction.commit();
    }
    //我们不能保证地图可用,因为谷歌播放
    //服务可能不可用。
    setUpMapIfNeeded(); // XXX这里的GetMap()这样的标记不能添加返回null
    //地图是示出与previous选项。
}

私人无效closeMap(){
    FragmentTransaction fragmentTransaction = getChildFragmentManager()的BeginTransaction()。
    fragmentTransaction.remove(mMapFragment);
    fragmentTransaction.commit();
}

私人无效setUpMapIfNeeded(){
    //做一个空检查确认,我们还没有实例化
    // 地图。
    如果(MMAP == NULL){
        //尝试获取来自SupportMapFragment地图。
        MMAP = mMapFragment.getMap();
        //检查如果我们成功取得地图。
        如果(MMAP!= NULL){
            mMap.addMarker(新MarkerOptions()位置(新的经纬度(37.4005502611301,-5.98233461380005))标题(标记));
        }
    }
}
}
 

感谢

解决方案

好AnderWebs给了我的的Google+ ,但他太LAZ .... EMM忙一遍写在这里,所以这里的短版: 延长 MapFragment 类和重写 onCreateView()方法。之后做了这种方法,我们可以得到一个非空引用阙 GoogleMap的对象。

这是我的特殊解决方案:

 公共类MiniMapFragment扩展SupportMapFragment {
    私人经纬度mPosFija;

    公共MiniMapFragment(){
        超();
    }

    公共静态MiniMapFragment的newInstance(经纬度职位){
        MiniMapFragment FRAG =新MiniMapFragment();
        frag.mPosFija =职位;
        返回FRAG;
    }

    @覆盖
    公共查看onCreateView(LayoutInflater为arg0,ViewGroup中ARG1,捆绑ARG2){
        视图V = super.onCreateView(为arg0,ARG1,ARG2);
        initMap();
        返回伏;
    }

    私人无效initMap(){
        UiSettings设置=的GetMap()getUiSettings()。
        settings.setAllGesturesEnabled(假);
        settings.setMyLocationButtonEnabled(假);

        。的GetMap()moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija,16));
        。的GetMap()addMarker(新MarkerOptions()位置(mPosFija).icon(BitmapDesc​​riptorFactory.fromResource(R.drawable.marker)));
    }
}
 

现在在previous片段类我

  mMapFragment = MiniMapFragment.newInstance(新经纬度(37.4005502611301,-5.98233461380005));
 

也许这不是很完美,因为显示的地图时,屏幕闪烁。但是不知道这个问题是因为这样或者别的什么的。

I'm trying to add a MapFragment to my current Fragment. The use of nested fragments is restricted to FragmentTransactions, you can't use the xml tag in your layout. Also, I want it to be added to the main Fragment when the user presses a button. So, I'm creating the MapFragment programmatically with getInstance() when the user presses that button and adding it to the proper place. It is shown correctly, so far so good.

The problem is that after attaching the MapFragment I need to get a reference to GoogleMap to place a Marker, but the getMap() method returns null (as the fragment's onCreateView() hasn't been called yet).

I looked at the demo example code and I found the solution they use is initializing the MapFragment in onCreate() and getting the reference to GoogleMap in onResume(), after onCreateView() has been called.

I need to get the reference to GoogleMap right after the MapFragment initialization, because I want the users to be able to show or hide the map with a button. I know a possible solution would be to create the Map at the start as said above and just set it's visibility gone, but I want the map to be off by default so it doesn't take the user's bandwidth if they don't explicitly asked for it.

I tried with the MapsInitializer, but doesn't work either. I'm kind of stuck. Any ideas? Here is my testing code so far:

public class ParadaInfoFragment extends BaseDBFragment {
// BaseDBFragment is just a SherlockFragment with custom utility methods.

private static final String MAP_FRAGMENT_TAG = "map";
private GoogleMap mMap;
private SupportMapFragment mMapFragment;
private TextView mToggleMapa;
private boolean isMapVisible = false;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_parada_info, container, false);
    mToggleMapa = (TextView) v.findViewById(R.id.parada_info_map_button);
    return v;
}

@Override
public void onStart() {
    super.onStart();
    mToggleMapa.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isMapVisible) {
                openMap();
            } else {
                closeMap();
            }
            isMapVisible = !isMapVisible;
        }
    });
}

private void openMap() {
    // Creates initial configuration for the map
    GoogleMapOptions options = new GoogleMapOptions().camera(CameraPosition.fromLatLngZoom(new LatLng(37.4005502611301, -5.98233461380005), 16))
            .compassEnabled(false).mapType(GoogleMap.MAP_TYPE_NORMAL).rotateGesturesEnabled(false).scrollGesturesEnabled(false).tiltGesturesEnabled(false)
            .zoomControlsEnabled(false).zoomGesturesEnabled(false);

    // Modified from the sample code:
    // It isn't possible to set a fragment's id programmatically so we set a
    // tag instead and search for it using that.
    mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(MAP_FRAGMENT_TAG);

    // We only create a fragment if it doesn't already exist.
    if (mMapFragment == null) {
        // To programmatically add the map, we first create a
        // SupportMapFragment.
        mMapFragment = SupportMapFragment.newInstance(options);
        // Then we add it using a FragmentTransaction.
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.parada_info_map_container, mMapFragment, MAP_FRAGMENT_TAG);
        fragmentTransaction.commit();
    }
    // We can't be guaranteed that the map is available because Google Play
    // services might not be available.
    setUpMapIfNeeded(); //XXX Here, getMap() returns null so  the Marker can't be added
    // The map is shown with the previous options.
}

private void closeMap() {
    FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
    fragmentTransaction.remove(mMapFragment);
    fragmentTransaction.commit();
}

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();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.addMarker(new MarkerOptions().position(new LatLng(37.4005502611301, -5.98233461380005)).title("Marker"));
        }
    }
}
}

Thanks

解决方案

The good AnderWebs gave me an answer in Google+ but he is too laz.... emm busy to write it here again, so here is the short version: Extend the MapFragment class and override the onCreateView() method. After this method is done we can get a non-null reference to que GoogleMap object.

This is my particular solution:

public class MiniMapFragment extends SupportMapFragment {
    private LatLng mPosFija;

    public MiniMapFragment() {
        super();
    }

    public static MiniMapFragment newInstance(LatLng posicion){
        MiniMapFragment frag = new MiniMapFragment();
        frag.mPosFija = posicion;
        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
        View v = super.onCreateView(arg0, arg1, arg2);
        initMap();
        return v;
    }

    private void initMap(){
        UiSettings settings = getMap().getUiSettings();
        settings.setAllGesturesEnabled(false);
        settings.setMyLocationButtonEnabled(false);

        getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija,16));
        getMap().addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
    }
}

Now in the previous Fragment class I do

mMapFragment = MiniMapFragment.newInstance(new LatLng(37.4005502611301, -5.98233461380005));

Maybe it's not perfect yet, because the screen blinks when showing the map. But not sure if the problem is because of this or something else.

这篇关于初始化MapFragment编程方式与地图API V2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆