Seïfane Idouchach Seïfane Idouchach - 5 months ago 24
Android Question

Add Google Maps API V2 in a fragment

I'm trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can't get the expected output.
Also I'm a beginner on this platform! What I really want is just a way to put a map from the Google Maps API V2 for Android in a fragment. Please share your ideas and references.

Thanks in Advance !

Answer

Use SupportMapFragment instead of MapFragment and use getActivity()

This is a basic example using SupportMapFragment:

public class MainActivity extends ActionBarActivity implements OnMapReadyCallback{

    private SupportMapFragment map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        map.getMapAsync(this);//remember getMap() is deprecated!      
    }

    @Override
    public void onMapReady(GoogleMap map) {
           map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(47.17, 27.5699), 16));      
            map.addMarker(new MarkerOptions()               .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                    .position(new LatLng(47.17, 27.5699))); //Iasi, Romania
            map.setMyLocationEnabled(true);     
    }
}

and change the reference in your layout:

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