Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add map fragment programmatically

I would like add this xml fragment programmatically to other fragments. Is it possible?

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
like image 940
user3910670 Avatar asked Apr 17 '15 11:04

user3910670


People also ask

What is MapFragment?

public class MapFragment extends Fragment. A Map component in an app. This fragment is the simplest way to place a map in an application. It's a wrapper around a view of a map to automatically handle the necessary life cycle needs.

What is getMapAsync?

getMap() is deprecated public void getMapAsync (OnMapReadyCallback callback) Sets a callback object which will be triggered when the GoogleMap instance is ready to be used. Note that: This method must be called from the main thread. The callback will be executed in the main thread.


2 Answers

In XML you can add a placeholder container:

<FrameLayout
        android:id="@+id/mapContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

And then in code you can do:

FragmentManager fm = getChildFragmentManager();
SupportMapFragment supportMapFragment =  SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, supportMapFragment).commit();
like image 200
Numan1617 Avatar answered Oct 18 '22 12:10

Numan1617


Make a layout like:

 <FrameLayout
    android:id="@+id/layout_mapContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_weight="0"
    android:background="@android:color/transparent"
    android:orientation="vertical" >

 <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" />
</FrameLayout>

In Activity declare :

FrameLayout mapLayout = (FrameLayout)findViewById(R.id.layout_mapContainer);

initialise map like this:

private void initialiseMap() {

        FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
        SupportMapFragment mFRaFragment = new MapFragmentActivity();
        mTransaction.add(mapLayout.getId(), mFRaFragment);
        mTransaction.commit();

        try {
            MapsInitializer.initialize(context);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Here MapFragmentActivity is class extends SupportMapFragment

like image 24
Pankaj Avatar answered Oct 18 '22 12:10

Pankaj