如何在一个碎片中获取Google地图对象

16

我正在使用应用程序中的片段,并且对此很生疏。有一个片段,我想在其中显示Google地图并获取其对象,因此我在我的XML文件中有一个片段,并且我想在片段本身中填充它。当我尝试填充地图视图时,它会显示一个getSupportFragmentManager()错误。

那么我该如何获取地图对象呢,这是主要问题。我的XML文件如下:

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

我的Fragment中,我想获取Google地图对象的代码如下:

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个回答

24

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 { /* ... */ }

然后,在初始化地图时,请使用getMapAsync()而不是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"/>

你能发一下XML代码吗?我在使用你的片段代码时遇到了这个错误:com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)在一个空对象引用上。 - Pablo Cegarra
1
这个答案是正确的,但你应该知道在一个Activity中,你必须继承自FragmentActivity,否则会出现问题。 - abolfazl bazghandi

21

试一下这个

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

4
getMap()已经过时。有什么可能的解决方案? - Recomer
2
getMapAsync(<OnMapReadyCallback>) 是 getMap() 的替代方法:https://dev59.com/zF0Z5IYBdhLWcg3wfgi- - rbs

6

我试过这个方法,很有效。 如何在ViewPager上使用Fragment添加Google Maps V2

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

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

希望这可以帮到你! - Michel
但这是针对FragmentActivity而不是Fragment的。 - 3k-

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。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接