How to get Google Maps object inside a Fragment
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" />
getMap() method is deprecated
getMap()
method is deprecated but after the play-services 9.2
it 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"/>