单独片段Android中的Mapview

单独片段Android中的Mapview

本文介绍了单独片段Android中的Mapview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个这样的mapview,假设我的主要活动是这样的
在这里,我的主要活动包含主要活动中的mapview实例,然后单击它,然后应使用android中的map活动打开一个新活动

I want to have a mapview like this suppose my main activity is like this
Here my main activity holds the instance of mapview in main activity and then when I click on it ,then a new activity should be opened with the map activity in android

推荐答案

您需要在XML文件中具有supportMapFragment,并将mapFragment的引用获取到MainFragment中.以下代码说明了如何在Fragment中完成MapView".在mapView.xml中编写以下XML代码,然后使用Fragment OnCreateView获取引用.

You need to have the supportMapFragment in your xml file and get the reference of mapFragment into your MainFragment. The below code explains, How I accomplished the MapView inside Fragment. Write the below XML code in the mapView.xml and then Use the Fragment OnCreateView to get references.

<片段xmlns:android ="http://schemas.android.com/apk/res/android"android:id ="@ + id/mainMap"android:name ="com.google.android.gms.maps.SupportMapFragment"android:layout_width ="match_parent"android:layout_height ="200dp"/>

public class MapInFragment extends Fragment implements OnMapReadyCallback {
private View rootView;
private GoogleMap mMap;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.mapView, container, false);





    try{
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mainMap);
        mapFragment.getMapAsync(MapInFragment.this);
    }catch (Exception e){
        e.printStackTrace();
    }

    return rootView;
}


@Override
public void onMapReady(GoogleMap googleMap) {
    try {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng croplatlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
        mMap.addMarker(new MarkerOptions().position(croplatlng).title(crop + "Field"));

        //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(croplatlng,16));

        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(croplatlng , 16);
        //mMap.addMarker(new MarkerOptions().position(location).title(""));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation ));
        mMap.animateCamera(cameraUpdate,2000,null);
    }catch (Exception e){
        e.printStackTrace();
    }

}


public void onDestroyView()
{
    try {
        Fragment fragment = (getChildFragmentManager().findFragmentById(R.id.mainMap));
        if (fragment != null) {
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.remove(fragment);
            ft.commit();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    super.onDestroyView();
}

}

这篇关于单独片段Android中的Mapview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:35