Android地图在应用程序加载不起作用时缩放到当前位置

Android地图在应用程序加载不起作用时缩放到当前位置,android,google-maps,android-fragments,Android,Google Maps,Android Fragments,我正在尝试编写一个代码,当应用程序加载时,它会将地图缩放到当前位置 这是我用来缩放地图的代码 //Zoom to the current location public Location getMyLocation() { LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); Criter

我正在尝试编写一个代码,当应用程序加载时,它会将地图缩放到当前位置

这是我用来缩放地图的代码

  //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
}
然后我在片段的
onCreateView
中调用了方法。 这是代码

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

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();


            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

            LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();

            String bestProvider = locationManager.getBestProvider(criteria, false);
            if(bestProvider != null)
            {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location != null)
                {
                    onLocationChanged(location);
                }
                locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
            }

        }

        return rootView;
    }
但是,我的代码似乎没有执行这个缩放部分

我对Android有点陌生,这是我在fragment中使用的第一个代码(我这么说是因为这对高级人员来说可能是一个低级问题)。那么,有人能告诉我有没有具体的方法来实现片段

提前感谢。:)

-编辑-

这是我的
GoogleMapsFragment.java

public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener {

    View rootView;
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);

    private GoogleMap map;

    public GoogleMapsFragment()
    {
    }

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

        if(!isGooglePlayServiceAvailable())
        {
           return null;
        }

        if(rootView != null)
        {
            ViewGroup parent = (ViewGroup)rootView.getParent();
            if(parent != null)
            {
                parent.removeView(rootView);
            }
        }
        else
        {
            rootView = inflater.inflate(R.layout.google_maps, container, false);
            map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();


            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

            LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();

            String bestProvider = locationManager.getBestProvider(criteria, false);
            if(bestProvider != null)
            {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location != null)
                {
                    onLocationChanged(location);
                }
                locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
            }

        }

        return rootView;
    }

    //Zoom to the current location
    public Location getMyLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null)
        {
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                    .zoom(17)                   // Sets the zoom
                    .bearing(90)                // Sets the orientation of the camera to east
                    .tilt(40)                   // Sets the tilt of the camera to 30 degrees
                    .build();                   // Creates a CameraPosition from the builder
            map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

        return location;
    }


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

        map.setMyLocationEnabled(true); // Identify the current location of the device

        Location currentLocation = getMyLocation(); // Calling the getMyLocation method
    }

    @Override
    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        map.addMarker(new MarkerOptions().position(latLng));
        map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    private boolean isGooglePlayServiceAvailable()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if(ConnectionResult.SUCCESS == status)
        {
            return true;
        }
        else
        {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }
}

1.实现接口

implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener
2.添加

 private GoogleApiClient mGoogleApiClient;  
 private GoogleMap mMap;
 private LatLng latlng;
3.
onCreateView
方法中添加此代码

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);

    if (mapFragment != null)
        mapFragment.getMapAsync(this);  

 if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            mGoogleApiClient.connect();
        }
 @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


        mMap.addMarker(new MarkerOptions().position(latlng).title("")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

//        // Zoom in, animating the camera.
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 3000, null);
        mMap.getUiSettings().setZoomControlsEnabled(false);
        mMap.getUiSettings().setCompassEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    }
4.
OnMapReady
方法

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);

    if (mapFragment != null)
        mapFragment.getMapAsync(this);  

 if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            mGoogleApiClient.connect();
        }
 @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;


        mMap.addMarker(new MarkerOptions().position(latlng).title("")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

//        // Zoom in, animating the camera.
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 3000, null);
        mMap.getUiSettings().setZoomControlsEnabled(false);
        mMap.getUiSettings().setCompassEnabled(false);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    }
5.
覆盖
方法
onConnected

 @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ContextCompat.checkSelfPermission(mActivity,
                android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null)
              latlng = new LatLng(location.getLatitude(),location.getLongitude());
            return;
        }
      //call onMapReady override method
     onMapReady(mMap);
    }
6.

 @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

在返回视图之前,您将调用缩放部分。所以,你永远看不到它。只需将缩放代码的animateCamera移动到onActivityCreated,或在Resume上,或在onCreateViewI添加整个片段后的任何方法中。你能说得更具体些吗?对Android来说有点陌生。所以,不知道有些方法是如何工作的(谢谢:)在类中添加名为onActivityCreated的新方法。如果您使用的是AndroidStudio,请单击类中的任意位置而不是内部方法,然后按ALT+Insert key>Override methods。这将显示所有可用的重写方法的列表。然后选择onActivityCreated。然后移动地图。setMyLocationEnabled(true);和位置currentLocation=getMyLocation();此方法的行。另外,请确保检查映射的空指针。在检查代码之前,我看到您使用的是
getMap()
,它已经被弃用了。您是否正在学习特定的教程?我建议首先研究最新的实现()。在这里,您可以看到不同之处,并建议使用类似
getmapsync()
的方法。另外,在运行quickstart之后,您可以继续按照您希望的方式修改代码。干杯!:)嗨,亚西尔·塔希尔,照你说的做了。请看我编辑的答案。仍然不走运:(我如何在MapReadyCallback上实现?我添加了我的整个GoogleMapsFragment.java。你能告诉我把这段代码放在哪里吗?Tranks.:)如果你在MapReadyCallback上实现,那么这个覆盖方法会自动生成,你的代码会正常工作但是,它并没有缩放到我当前的位置。它正在缩放到标记所在的位置:(大家好,我正在尝试更改map.animateCamera(CameraUpdateFactory.zoomTo(6),5000,null)到我当前的位置。仍然没有运气:(嘿,很抱歉延迟重播,请检查我编辑的答案。它将放大最后一个当前位置。而且别忘了在gradle中添加google play服务,并在manifest中添加Delclariation。希望它对您有用。祝您好运,优质产品