打开我的应用程序时如何将相机移动到当前位置?

时间:2018-09-24 14:01:53

标签: android

我需要你的帮助。

打开应用程序后,如何立即将相机移动到当前位置?

我有一个可以使用的按钮(如果单击它,它将使照相机移动到当前位置),但是当我打开该应用程序时,照相机被设置在大海的中央。 我想打开应用程序,并且相机已经设置在当前位置。

这是我的代码:

MapsActivity.java

    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationManager;
    import android.os.Build;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.FragmentActivity;
    import android.os.Bundle;
    import android.support.v4.content.ContextCompat;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
    import com.google.android.gms.common.GooglePlayServicesRepairableException;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.common.api.GoogleApi;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.CameraUpdate;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener, LocationListener {

        private GoogleMap mMap;
        private GoogleApiClient googleApiClient;
        private LocationRequest locationRequest;
        private Location lastLocation;
        private Marker currentUserLocationMarker;
        private static final int Request_User_Location_Code = 99;


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

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                checkUserLocationPermission();
            }

            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        /**
         * Manipulates the map once available.
         * This callback is triggered when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera. In this case,
         * we just add a marker near Sydney, Australia.
         * If Google Play services is not installed on the device, the user will be prompted to install
         * it inside the SupportMapFragment. This method will only be triggered once the user has
         * installed Google Play services and returned to the app.
         */

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

            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
            /*disabling toolbar (it is used to continue using this app without having to
            use the official google maps app)*/

            mMap.getUiSettings().setMapToolbarEnabled(false);
        }

        public boolean checkUserLocationPermission(){
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code );
                }
                else{
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code );
                }
                return false;
            }
            else{
                return true;
            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode){
                case Request_User_Location_Code:
                    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                            if(googleApiClient == null){
                                buildGoogleApiClient();
                            }
                            mMap.setMyLocationEnabled(true);
                        }
                    }
                    else{
                        Toast.makeText(this, "Permesso vietato", Toast.LENGTH_SHORT).show();
                    }
                    return;
            }
        }

        protected synchronized void buildGoogleApiClient(){

            googleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            googleApiClient.connect();


        }

        @Override
        public void onLocationChanged(Location location) {
            lastLocation = location;

            if(currentUserLocationMarker != null){
                currentUserLocationMarker.remove();
            }

            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

            MarkerOptions markerOptions = new MarkerOptions();

            markerOptions.position(latLng);
            markerOptions.title("Posizione corrente");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

            currentUserLocationMarker = mMap.addMarker(markerOptions);

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomBy(11));

            if (googleApiClient != null){
                LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
            }
        }

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

            locationRequest = new LocationRequest();
            locationRequest.setInterval(1100);
            locationRequest.setFastestInterval(1100);
            locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
            }
        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        }
}

activity_maps.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"
    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"
    tools:context=".MapsActivity"
    class="com.google.android.gms.maps.SupportMapFragment"/>

已将其添加到我的 AndroidManifest.xml 中:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

因此,您已经完成了几乎所有的工作。您只需要再走一步即可。

首先要了解的是,将setMyLocationEnabled设置为true时会在地图上添加该位置指南针按钮。这是您单击以查找当前位置的内容。好的开始。

初始化地图时,还需要将相机设置为当前位置。

if(locationPermissionGranted){
            Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
            locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {
                    if(task.isSuccessful()){
                        // Set the maps camera to current location
                        lastKnownLocation = task.getResult();
                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()), 12));
                    }
                    else{
                        Log.d(TAG, "Current location is null");
                        Log.e(TAG,"Exception: %s", task.getException());
                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 12));
                        map.getUiSettings().setMyLocationButtonEnabled(false);
                    }
                }
            });
        }

尝试一下。首先,请确保您已授予位置权限。然后尝试找到最后一个已知的位置。 (如果您使用的是模拟器,请在尝试使用此代码之前先尝试打开Goog​​le Maps。从未在模拟器上启动过位置服务)。它将尝试获取您的当前位置。如果成功,它将照相机移动到该位置,如果失败,我将为地图设置默认位置,而不是在海洋中打开。

private LatLng defaultLocation = new LatLng(41.651031, -83.541939);

希望这会有所帮助。

答案 1 :(得分:0)

我想,我是这样解决的。

我已经修改了 onMapReady

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    float zoomLevel = 15.0f;
                    LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
                }
            });

        }
        /*disabling toolbar (it is used to continue using this app without having to
        use the official google maps app)*/
        mMap.getUiSettings().setMapToolbarEnabled(false);

然后,当我打开我的应用程序时,会将相机设置在我的当前位置。 非常感谢。

答案 2 :(得分:0)

[前提条件]-确保您已授予位置权限,并且位置服务已打开。

public void onMapReady(GoogleMap googleMap){
    mMap = googleMap;
    // You can register for Location Change Once the location is updated,
    // Fetch lat, lng from it. Once you have lat,lng convert it into `LatLng`
    LatLng currLatLng = fetchedFromAPI();
    CameraPosition newPos =
                new CameraPosition.Builder()
                        .target(currLatLng)
                        .build();
    if (showAnimation){
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(newPos));
    }else{
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(newPos));
    }
}