如何在Fragment中获取Google Maps对象

时间:2014-02-26 05:44:06

标签: android google-maps android-fragments fragment google-maps-android-api-2

我在我的应用程序中使用片段,我是新手。有一个片段,我想要显示谷歌地图,并希望得到它的对象,为此我在我的XML中有一个片段,我想在片段本身膨胀它。当我试图给地图视图充气时,它显示了getSupportFragmentManager()的错误。

如何获取地图对象,那是主要问题。我的XML是这样的: -

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

我想要获取Google Map对象的Fragment就是这样: -

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);
    }

有人可以帮助我获取地图的对象,以便我可以显示当前位置并在那里绘制标记。

任何帮助都会很明显。 提前谢谢。

7 个答案:

答案 0 :(得分:19)

试试这个

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

和你的xml

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

答案 1 :(得分:17)

getMap()方法已被删除

getMap()方法已弃用,但在删除play-services 9.2之后,最好使用getMapAsync()。只有在您不愿意更新应用的play-services 9.2时,您仍然可以使用getMap()。

要使用getMapAsync(),请在您的活动或片段上实施OnMapReadyCallback界面:

对于片段

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
}

活动

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
}

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

答案 2 :(得分:6)

试试这个对我有用 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();

答案 3 :(得分:2)

尝试这个我根据您的需要将其作为样本

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"));
    }
}

答案 4 :(得分:1)

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;

}

您可以使用它来制作地图,但它会返回地图对象为空,因为您没有找到使用getMapAsync创建新对象mMap的解决方案。它只返回null的后台任务

答案 5 :(得分:1)

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

View root= inflater.inflate(R.layout.fragment_a_t_m_locations, container, false);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map);
    mapFragment.getMapAsync(googleMap -> {
        mMap=googleMap;
        if(mMap!=null){
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        }
    });

答案 6 :(得分:0)

修改后的代码:

你的xml文件 -

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

您的java文件(仅相关代码) -

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);