How to get Google Maps object inside a Fragment

2019-04-04 01:16发布

问题:

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 my XML and I want to inflate it in the Fragment itself. When I am trying to inflate the map view its showing me error for getSupportFragmentManager().

How do I get the map object then that is the main issue. My XML is like this :-

 <fragment
                android:id="@+id/map"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                class="com.google.android.gms.maps.SupportMapFragment" />

And my Fragment in which I want to get the Google Map object is like that :-

public class FindMyCar extends Fragment {

    private TextView mTvFind;
    private TextView mTvPark;
    private EditText mEtParkHint;

    private GoogleMap map;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.findmycar, null);

        initViews(view);

        Typeface type = Typeface.createFromAsset(getActivity().getResources().getAssets(),"Multicolore.otf"); 
        mTvFind.setTypeface(type);
        mTvPark.setTypeface(type);
        mEtParkHint.setTypeface(type);

        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);


        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void initViews(View view){


        mTvPark = (TextView) view.findViewById(R.id.tvFindCarPark);
        mTvFind = (TextView) view.findViewById(R.id.tvFindCar);
        mEtParkHint = (EditText) view.findViewById(R.id.etParkHint);
    }

Can someone help me to get the object for my map so that I can show current location and draw the marker there.

Any help would be appreciable. Thanks in advance.

回答1:

Try this

 GoogleMap map = ((SupportMapFragment) getFragmentManager()
                .findFragmentById(R.id.map)).getMap();

and in your xml

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />


回答2:

getMap() method is depricated

getMap() method is depreciated 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

   <fragment  xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


回答3:

Try this it works for me How to put Google Maps V2 on a Fragment Using ViewPager

<Fragment
            android:id="@+id/map"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />

GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();


回答4:

Try this i have made this as a sample according to your need

public class LocationMapActivity extends FragmentActivity {
    private GoogleMap mMap;
    static boolean Iscamera = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.locatio_map);

        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();

    }

    private void setUpMapIfNeeded() {

        if (mMap == null) {

            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            mMap.setMyLocationEnabled(true);

            if (mMap != null) {

                mMap.setMyLocationEnabled(true);
                mMap.getUiSettings().setCompassEnabled(true);
                mMap.getUiSettings().setZoomControlsEnabled(true);
                mMap.getMaxZoomLevel();
                mMap.getMinZoomLevel();
                mMap.getUiSettings();
                mMap.animateCamera(CameraUpdateFactory.zoomIn());
                mMap.animateCamera(CameraUpdateFactory.zoomOut());
                mMap.animateCamera(CameraUpdateFactory.zoomTo(20));

                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                    @Override
                    public void onMyLocationChange(Location arg0) {
                        // TODO Auto-generated method stub

                        mMap.clear();
                        mMap.addMarker(new MarkerOptions()
                        .position(
                                new LatLng(arg0.getLatitude(), arg0
                                        .getLongitude()))
                        .title("I am Here!!")
                        .icon(BitmapDescriptorFactory
                                .fromResource(R.drawable.map_icon)));
                        if (!Iscamera) {
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                    new LatLng(arg0.getLatitude(), arg0
                                            .getLongitude()), 14));


                            Iscamera = true;
                        }
                        try {

                            if (Constant.FORTNAME.equals("Arad Fort")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(new LatLng(26.2525, 50.6269))
                                        .title(Constant.FORTNAME)
                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME.equals("Bahrain Fort")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.2333598,
                                                        50.52035139))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));
                            } else if (Constant.FORTNAME
                                    .equals("International Circuit")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.0303251,
                                                        50.51121409))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME
                                    .equals("Khamis Mousque")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.158719, 50.516426))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME
                                    .equals("king fahad causeway")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.1723987,
                                                        50.4579942))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME.equals("Riffa Fort")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.11771965026855,
                                                        50.56298065185547))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME
                                    .equals("Royal Golf Club")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(26.13000, 50.55500))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            } else if (Constant.FORTNAME.equals("Tree of life")) {
                                mMap.addMarker(new MarkerOptions()
                                        .position(
                                                new LatLng(25.9940396,
                                                        50.583135500000026))
                                        .title(Constant.FORTNAME)

                                        .icon(BitmapDescriptorFactory
                                                .fromResource(R.drawable.greenicon)));

                            }

                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(),
                                    e.getMessage(), Toast.LENGTH_LONG).show();
                            Log.e(e.getClass().getName(), e.getMessage(), e);
                        }

                    }
                });

            }
        }

    }

    // ********************************************************************************************
    @SuppressWarnings("unused")
    private void setUpMap() {

        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
                "Marker"));
    }
}


回答5:

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;

}

You can use this to making map but it will return map object is null because you don't find solution with getMapAsync to create a new object mMap. It only background task with return null



回答6:

Revised code:

Your xml file-

 <fragment 
      android:name="com.google.android.gms.maps.SupportMapFragment"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

Your java file (only relevant code)-

View  view = null, mapView = null;
private GoogleMap mMap;

view = inflater.inflate(R.layout.findmycar, container,false);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
                .findFragmentById(R.id.map);

mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);