如何在Fragment中使用SupportMapFragment?

时间:2014-07-31 05:11:13

标签: android google-maps supportmapfragment

我知道使用嵌套片段存在问题。但是我的应用程序设计为在片段上运行,如果我将使用地图的活动,我的强制转换功能将会出错。

我想请教您如何实现这一目标。我一直在网上搜索,但我无法找到最佳解决方案。

我已尝试过此代码:

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) myFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.map_con))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
}

这会给我重复的错误,因为R.id.map_con是我片段中的一个片段。

所以我寻找一个解决方法,这次,R.id.map_con是一个框架布局,在运行时我创建了SupportMapFragment。

SupportMapFragment mSupportMapFragment = new SupportMapFragment();
    myFragmentActivity.getSupportFragmentManager().beginTransaction()
            .replace(R.id.map_con, mSupportMapFragment).commit();

虽然每次关闭并打开片段时都没有给我重复。但我的错误是mSupportMapFragment.getMap总是为空。我不知道为什么它为null?。

mMap = mSupportMapFragment.newInstance().getMap();
        if (mMap != null){
            Log.e("ReportFragment","mMap is not empty");
        }else{
            Log.e("ReportFragment","mMap is empty");
        }

我真的很感谢你们提出的任何意见,或者你们还有另外的工作但仍然在这个过程中,即片段内的片段

谢谢

chkm8

5 个答案:

答案 0 :(得分:46)

getMap()已弃用

Fragment中的代码应该是这样的:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_location, container, false);

    mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mMapFragment.getMapAsync(this);

    return v;   
}

答案 1 :(得分:19)

我刚刚遇到运气,在发布这篇文章时,我找到了我想要的东西。

我用过这个:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_location, container, false);
    mMapFragment = new SupportMapFragment() {
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            mMap = mMapFragment.getMap();
            if (mMap != null) {
                setupMap();
            }
        }
    };
    getChildFragmentManager().beginTransaction().add(R.id.framelayout_location_container, mMapFragment).commit();
return v;   
}

归功于此Old post

答案 2 :(得分:5)

  

我已经以给定的方式使用它并且它正常工作。

它也在使用getChildFragmentManager()

<强> MapyFragment

public class MapyFragment extends Fragment implements OnMapReadyCallback {

    private Context mContext;
    private SupportMapFragment supportMapFragment;
    private GoogleMap map;
    private MarkerOptions currentPositionMarker = null;
    private Marker currentLocationMarker;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getActivity();
        return inflater.inflate(R.layout.fragment_mapy, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mContext = getActivity();

        FragmentManager fm = getActivity().getSupportFragmentManager();/// getChildFragmentManager();
        supportMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
        if (supportMapFragment == null) {
            supportMapFragment = SupportMapFragment.newInstance();
            fm.beginTransaction().replace(R.id.map_container, supportMapFragment).commit();
        }
        supportMapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        map.setMyLocationEnabled(true);
        map.animateCamera(CameraUpdateFactory.zoomTo(15));
        /*map.setOnMapLongClickListener(MapyFragment.this);
        map.setOnMapClickListener(MapFragment.this);*/
    }

    public void updateCurrentLocationMarker(Location currentLatLng){

        if(map != null){

            LatLng latLng = new LatLng(currentLatLng.getLatitude(),currentLatLng.getLongitude());
            if(currentPositionMarker == null){
                currentPositionMarker = new MarkerOptions();

                currentPositionMarker.position(latLng)
                        .title("My Location").
                        icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
                currentLocationMarker = map.addMarker(currentPositionMarker);
            }

            if(currentLocationMarker != null)
                currentLocationMarker.setPosition(latLng);

            ///currentPositionMarker.position(latLng);
            map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        }
    }
}

fragment_mapy.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map_container"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    map:uiZoomControls="true" />

答案 3 :(得分:0)

kotlin 中,可以按以下步骤操作:

class NameFragment: Fragment(){
    // other code ...
    private lateinit var googleMapsFragment: SupportMapFragment

    override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
         googleMapsFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment
        // other code ...
    }
}

答案 4 :(得分:0)

在 Java 中创建 SupportMapFragment?

您也可以像这样在 Fragment 中创建 SupportMapFragment。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_maps, parent, false);
    SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();

    getChildFragmentManager()
        .beginTransaction()
        .add(R.id.mapContainer, supportMapFragment)
        .commit();

    supportMapFragment.getMapAsync(this::onMapReady);
    
    return view;
}

这是布局R.layout.fragment_maps的代码

<androidx.coordinatorlayout.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
       android:id="@+id/map"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
    />
    <!-- Other Widgets like FAB, Bottomsheet-->
</androidx.coordinatorlayout.widget.CoordinatorLayout>

注意:

这是在活动中膨胀片段的常见做法。

  • 创建片段的实例
  • 在片段容器中对其进行充气

所以我采用了相同的方法在 Fragment 内膨胀 SupportMapFragment。