1

I am having a lot of trouble getting .getMap() to work when trying to create a GoogleMap object (it is returning null), I have looked around and seen people had similar issues but wasn't able to find any help from any of them. In it's current implementation how can I find the MapFragment & create a GoogleMap from it?

protected void setFragment(){
    FragmentManager fm = getFragmentManager();
    MapFragment mapFragment =  MapFragment.newInstance();
    fm.beginTransaction().replace(R.id.fragment_container, mapFragment).commit();

    try{
        GoogleMap gMap = ((MapFragment)fm.findFragmentById(R.id.fragment_container)).getMap();
        gMap.setBuildingsEnabled(true);
    }catch(Exception e){  }

}

The portion of XML containing fragment_container

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:id="@+id/selectionLayout">


    <RelativeLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="85dp">


    </RelativeLayout>

</RelativeLayout>
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
Galax
  • 367
  • 1
  • 13

2 Answers2

2

Allow the Map to load before you start using otherwise you'll get null. You have the onReady callback when the map is ready for use.

protected void setFragment(){
    FragmentManager fm = getFragmentManager();
    MapFragment mapFragment =  MapFragment.newInstance();
    fm.beginTransaction().replace(R.id.fragment_container, mapFragment).commit();

    try{
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap map) {
                //your map related actions.
            }
        });
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}
durron597
  • 31,968
  • 17
  • 99
  • 158
Harish Sridharan
  • 1,070
  • 6
  • 10
  • @DanielNugent good catch! It was a duplicate variable as well. I just copy pasted the code from the question. – Harish Sridharan Aug 04 '15 at 15:51
  • Accepted as answer, however it was missing a required closing parenthesis which I requested as an edit. Thanks! – Galax Aug 05 '15 at 15:03
-2

You actually need to include a fragment (NOT the Relative Layout) to your layout like so:

<fragment
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
Sree
  • 2,727
  • 3
  • 29
  • 47