简体   繁体   中英

Unable to use google map V2 inside fragment

I know this question has already been asked a few times, but I cant find a solution to my problem by looking at them. I have created a navigation drawer. The navigation drawer naturally helps switching fragments. Inside one such fragment, I want to show up a google map.

The map_fragment.xml :

<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.MapFragment" />

The MapFragment :

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;



public class MapFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.map_fragment, container, false);

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


     }


}

The line:

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

Always shows:

Cannot cast from Fragment to SupportMapFragment

I am not sure why is this showing up? Where am I going wrong? I have provided all the required permissions in the Manifest as I am able to see google map in other activities.

This is best practice to use google map , try it.

public class MapFragment extends Fragment implements OnMapReadyCallback{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.map_fragment, container, false);

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

    map.getMapAsync(this);
return view;


 }

@Override
public void onMapReady(GoogleMap googleMap) {
    //googleMap is your map

    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    gm = googleMap;

    googleMap.setOnMarkerClickListener(this);

    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Ancona, 5));
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM