Android 如何在片段中使用谷歌地图

Android 如何在片段中使用谷歌地图,android,maps,fragment,Android,Maps,Fragment,我想把这个类放在一个片段中,我怎样才能把它放在一个片段类中呢 public class MapsActivity extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. @Override protected void onCreate(Bundle savedInstanceState) {

我想把这个类放在一个片段中,我怎样才能把它放在一个片段类中呢

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    } 
我需要这些方法在我的片段中工作。但是我没法按这个按钮

    public void onSearch(View view) {
        EditText location_tf = (EditText) findViewById(R.id.TFaddress);
        String location = location_tf.getText().toString();
        List<Address> addressList = null;
        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);


            } catch (IOException e) {
                e.printStackTrace();
            }
                Address address = addressList.get(0);
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
    }
        public void onZoom(View view) {
        if (view.getId() == R.id.Bzoomin) {
            mMap.animateCamera(CameraUpdateFactory.zoomIn());
        }
        if (view.getId() == R.id.Bzoomout) {
            mMap.animateCamera(CameraUpdateFactory.zoomOut());
        }
    }

    public void changeType(View view) {
        if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        } else
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }

    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) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

片段类应该是这样的

public MyMapFragment extends Fragment{

 private GoogleMap map;
    public GoogleApiClient mGoogleApiClient;
    private LocationRequest locationRequest;
    private Location myLocation;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

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

        map = ((MapFragment) act.getFragmentManager()
                .findFragmentById(R.id.map)).getMap();
        map.getUiSettings().setRotateGesturesEnabled(false);
        map.getUiSettings().setZoomControlsEnabled(false);
        map.setTrafficEnabled(true);
        map.setOnMarkerDragListener(dragListener);
        map.setOnMapLongClickListener(longClickListener);

    }

 @Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    }

 private void showCurrentLocation(Location location) {
        if (map.getCameraPosition().zoom < MAP_ZOOM_LEVEl) {
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
                    location.getLatitude(), location.getLongitude()), 12));
        }
        CameraPosition cameraPosition = new CameraPosition(new LatLng(
                location.getLatitude(), location.getLongitude()),
                map.getCameraPosition().zoom, 45, 360);
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }

@Override
    public void onConnected(@Nullable Bundle bundle) {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (myLocation != null) {
            showCurrentLocation(myLocation);
            return;
        }
        if ("Check for GPS Status")
           Show the error if not enabled
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, locationRequest, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        if (location == null)
                            return;
                        myLocation = location;
                        showCurrentLocation(location);
                    }
                });


    }

    protected void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setFastestInterval(FASTEST_INTERVAL);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

@Override
    public void onStop() {
        super.onStop();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
            mGoogleApiClient.disconnect();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        MapFragment mapFragment = (MapFragment) getActivity()
                .getFragmentManager().findFragmentById(R.id.map);
        if (mapFragment != null)
            getActivity().getFragmentManager().beginTransaction()
                    .remove(mapFragment).commit();
    }
}
公共MyMapFragment扩展片段{
私人谷歌地图;
公共GoogleapClient MGoogleapClient;
私人位置请求位置请求;
私人位置;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mGoogleApiClient=new-GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
@凌驾
已创建活动上的公共void(Bundle savedInstance){
super.onActivityCreated(savedInstance);
map=((MapFragment)act.getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.getUiSettings().setRotategestureEnabled(false);
map.getUiSettings().setZoomControlsEnabled(false);
map.setTrafficEnabled(true);
map.setOnMarkerDragListener(dragListener);
map.setOnMapLongClickListener(longClickListener);
}
@凌驾
public void onStart(){
super.onStart();
if(mGoogleApiClient!=null)
mGoogleApiClient.connect();
}
私有void showCurrentLocation(位置){
if(map.getCameraPosition().zoomBuild.VERSION\u code.LOLLIPOP){
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予
&&ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予){
返回;
}
}
myLocation=LocationServices.FusedLocationApi.getLastLocation(mgoogleAppClient);
if(myLocation!=null){
显示当前位置(myLocation);
返回;
}
如果(“检查GPS状态”)
如果未启用,则显示错误
LocationServices.FusedLocationApi.RequestLocationUpdate(
MGoogleapClient、locationRequest、new LocationListener(){
@凌驾
已更改位置上的公共无效(位置){
if(位置==null)
返回;
myLocation=位置;
showCurrentLocation(位置);
}
});
}
受保护的void createLocationRequest(){
locationRequest=新的locationRequest();
locationRequest.SetFastTestInterval(最快间隔);
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
}
@凌驾
公共void onStop(){
super.onStop();
if(mGoogleApiClient!=null&&mGoogleApiClient.isConnected()
mGoogleApiClient.disconnect();
}
@凌驾
公共无效onDestroyView(){
super.onDestroyView();
MapFragment MapFragment=(MapFragment)getActivity()
.getFragmentManager().findFragmentById(R.id.map);
if(mapFragment!=null)
getActivity().getFragmentManager().beginTransaction()
.remove(mapFragment.commit();
}
}
该片段的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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



</RelativeLayout>

在我的项目中,地图的实现方式如下:

没有meu项目实施地图:

public class MainFragment extends Fragment implements OnMapReadyCallback {


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_main, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    fragment.getMapAsync(this);
} }

对我有用的是这个

childFragmentManager.fragments[0] as SupportMapFragment?
让我解释一下:我有一个片段:地图片段,里面有另一个弗拉格门尔和地图,所以它是他的独生子。请注意,我认为这不是最佳做法,但我目前正在工作

class MapFragment : Fragment(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val rootView: View = inflater.inflate(R.layout.fragment_map, container, false)
    val mapFragment =
        childFragmentManager.fragments[0] as SupportMapFragment?
    mapFragment!!.getMapAsync(this)
    return rootView
}

override fun onMapReady(googleMap: GoogleMap?) {
    mMap = googleMap!!
    // Add a marker in Sydney and move the camera
    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
 }
}
我的片段的xml是

     <?xml version="1.0" encoding="utf-8"?>
     <FrameLayout 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"
    tools:context=".ui.MainActivity">
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>

这对我来说很有效,但我如何在Zoom和changeType上实现我的onSeach方法呢?
     <?xml version="1.0" encoding="utf-8"?>
     <FrameLayout 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"
    tools:context=".ui.MainActivity">
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>