Y
Y
ymi2016-03-01 17:14:00
Android
ymi, 2016-03-01 17:14:00

How to get the current location?

I am writing code according to google guidelines and various tutorials, but I still can’t pull out the current location
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) always returns null

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

        mHelpButton = (ImageButton)findViewById(R.id.helpButton);
        mHelpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelpDialog();
            }
        });

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
 @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "Location services connected.");
        
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_ACCESS_LOCATION);
        } else {
            // permission has been granted, continue as usual
            mCurrentLocation =
                    LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
        if (mCurrentLocation != null) {
            mUserLocation = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
            // Blank for a moment...
        }
    }

What could be the reason?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question