How to get Google Maps object inside a Fragment

前端 未结 7 1994
走了就别回头了
走了就别回头了 2021-02-19 01:26

I am using fragments in my application and I am new for this. There is a fragment in which I want to display Google Map and want to get its object, for this I have a fragment in

7条回答
  •  爱一瞬间的悲伤
    2021-02-19 01:53

    getMap() method is deprecated

    getMap() method is deprecated but after the play-services 9.2it is removed, so better use getMapAsync(). You can still use getMap() only if you are not willing to update the play-services 9.2 for your app.

    To use getMapAsync(), implement the OnMapReadyCallback interface on your activity or fragment:

    For fragment:

    public class MapFragment extends android.support.v4.app.Fragment
          implements OnMapReadyCallback { /* ... */ }
    

    Then, while initializing the map, use getMapAsync() instead of getMap():

    //call this method in your onCreateMethod
     private void initializeMap() {
      if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
        mapFrag.getMapAsync(this);
      }
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        setUpMap();// do your map stuff here
    }
    

    For Activity:

    public class MapActivity extends FragmentActivity
          implements OnMapReadyCallback { }
    Then, while initializing the map, use getMapAsync() instead of getMap():
    
    
    //call this method in your onCreateMethod
     private void initializeMap() {
      if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
        mapFrag.getMapAsync(this);
      }
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        setUpMap();// do your map stuff here
    }
    

    Fragment in XML:

       
    

提交回复
热议问题