Thursday, July 10, 2014

Displaying Google Map Inside Android Fragment

Display Google Fragment Maps in a Tab Fragment


Problem



I had problems finding information on how to display the Google map fragment within a tab pager.

This is a real problem because fragments are used extensively in master detail, tabs and navigation drawer patterns.

The solution was simple so I decided to post it, hope it helps some one.


I have an application where a user can select a contact, and then display details for the contact in tabs, for example all photos we have taken for this contact (from my EasySnap application), incoming and outgoing calls , address etc…




The user can move from one set of details to the next by selecting a Tab or swiping. The content for each tab is in a Fragment. I was unable to add the Google Map Fragment which would display the contacts location to a Tab fragment.
The problem was that until recently you could not add a Fragment to a Fragment, even now you can not create static fragments within a fragment.

Solution

You can now create fragments in Fragments if you create them dynamically in the fragment code.

1. Create a container for the Map Fragment in the layout for the tab fragment which will contain the map.


<FrameLayout

          android:layout_width="match_parent"

          android:layout_height="0dp"
          android:layout_weight="1.03"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:id="@+id/mapwhere" />

2. We create the Map fragment in the code of the tab which displays the "Map" fragment. One important thing to note is we use getChildFragmentManager() to access the Fragment manager because we are in a fragment.


public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.mapwhere);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapwhere, fragment).commit();
}

}
3. Gotcha To add locations to the map we need a pointer to the map created in the code above using map = fragment.getMap(); , it is tempting to add this code in the on ActivityCreated above, But the fragment references is not available until the onResume method is called.

With a reference to the map we can start adding locations as follows


map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"));



No comments:

Post a Comment