Android Google Maps V2 current position latitude l

2019-05-10 02:49发布

问题:

There are a lot of similar question but I don't find any solution for my problem. The setUpMap method is:

private void setUpMap() {
    BitmapDescriptor iconm = BitmapDescriptorFactory.fromResource(R.drawable.m);
    BitmapDescriptor iconc = BitmapDescriptorFactory.fromResource(R.drawable.c);
    // Enable MyLocation Layer of Google Map
    mMap.setMyLocationEnabled(true);
    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();
    // Get the name of the best provider
    String provider;
    provider = locationManager.getBestProvider(criteria,true);
    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);
    // getting GPS status
    boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    // getting network status
    boolean isNWEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isNWEnabled)
    {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(getString(R.string.askposition) );
        dialog.setPositiveButton(getString(R.string.settings), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);
            }
        });
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
            }
        });
        dialog.show();
        // no network provider is enabled
        Log.e("Current Location", "Current Lat Lng is Null");
    }
    else
    {
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled){
            if (myLocation == null) {
                if (locationManager != null) {
                    myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    double latitude = myLocation.getLatitude();
                    double longitude = myLocation.getLongitude();
                    LatLng latlng = new LatLng(latitude, longitude);
                    //myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    //double latitude = myLocation.getLatitude();
                    //double longitude = myLocation.getLongitude();
                    //String lati = String.valueOf(latitude);
                    //String longi = String.valueOf(longitude);
                    // Create a LatLng object for the current location
                    //LatLng latlng = new LatLng(latitude, longitude);
                    // set map type
                    //mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    //CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(12).build();

                    //mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                    // Show the current location in Google Map
                   // mMap.moveCamera(newLatLng(latlng));
                    // Zoom in the Google Map
                    //mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                }
            }
        }
        else {
            // First get location from Network Provider
            if (isNWEnabled) {
                if (myLocation == null) {
                    if (locationManager != null) {
                        myLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        double latitude = myLocation.getLatitude();
                        double longitude = myLocation.getLongitude();
                        LatLng latlng = new LatLng(latitude, longitude);
                        //double latitude = myLocation.getLatitude();
                        //double longitude = myLocation.getLongitude();

                        // Create a LatLng object for the current location
                        //LatLng latlng = new LatLng(latitude, longitude);
                        // set map type
                        //mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                        // Zoom in the Google Map
                        //CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(12).build();

                        //mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        //mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
                        // Show the current location in Google Map
                        //mMap.moveCamera(newLatLng(latlng));
                    }
                }
            }}
        }

    double latitude = myLocation.getLatitude();
    double longitude = myLocation.getLongitude();
    LatLng latlng = new LatLng(latitude, longitude);

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latlng).zoom(11).build();
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

It works fine when I first Run the app from Android Studio to my device, also works fine if I close and restart the application. But when I reboot my smartphone it gives me NullPointerException @ double latitude = myLocation.getLatitude(); and from that moment it crash always. How could I fix it? The commented code lines are about few attempts. Same problem at all. Any help would be much appreciated. Thanks in advance.

回答1:

I think a workaround for your problem is to use PASSIVE_PROVIDER.

Sample code:

    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
    myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    double longitude = myLocation.getLongitude();
    double latitude = myLocation.getLatitude();

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        }
    }


回答2:

Complete solution including permission check for Marshmallow and above

//get location manger instance
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);


   //check if we have permission to access device location
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    //add location change listener with update duration 2000 millicseconds or 10 meters
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new LocationListener() {
        public void onLocationChanged(Location location) {
            currentLongitude = location.getLongitude();
            currentLatitude = location.getLatitude();
        }

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

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }

    });


    //get last known location to start with  
    Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);    
    currentLatitude = myLocation.getLatitude();
    currentLongitude = myLocation.getLongitude();