0

I am new in android and i want to fetch my current location longitude and latitude and i have used this code to fetch my latitude and longitude and i cannot see the results in my logcat and i have also moved the google-services.json file app/ and intialised the mGoogleApiClient and mLastLocation and i am not getting any error then why i am not able to see the latitude and longitude.Please help me and thanks in advance here is the complete code of my app https://github.com/akashmalla07/GoogleMap please have a look if anyone can help me

Here is the code of Mapsactivity

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

         private GoogleMap mMap; 
         AppLocationService appLocationService;
         GoogleApiClient mGoogleApiClient;
         private Location mLastLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
                .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                .addApi(LocationServices.API).build();

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);
       setUpMapIfNeeded();

    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((SupportMapFragment) 
            getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            if (mMap != null) {
                displayLocation();
            }
        }
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            Log.d("result", latitude + ", " + longitude);

        } else {

          Log.d("result3","(Couldn't get the location. Make sure location is 
          enabled on the device)");
        }
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

And these are the imports

  import android.location.Location;
  import android.os.Bundle;
  import android.support.v4.app.FragmentActivity;
  import android.util.Log;

  import com.google.android.gms.common.ConnectionResult; 
  import com.google.android.gms.common.api.GoogleApiClient;
  import com.google.android.gms.location.LocationListener;
  import com.google.android.gms.location.LocationServices;
  import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.SupportMapFragment;

Updated code-------------------------------------------

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

private static final String TAG = MapsActivity.class.getSimpleName();
private LocationRequest mLocationRequest;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private GoogleMap mMap;
AppLocationService appLocationService;
GoogleApiClient mGoogleApiClient;
private Location mLastLocation;

private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    lblLocation = (TextView) findViewById(R.id.lblLocation);
    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    btnStartLocationUpdates = (Button) 
      findViewById(R.id.btnLocationUpdates);

    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();

      }

    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            displayLocation();
            Log.d("clicked","yes");
        }
    });

}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
        return false;
    }
    return true;
}

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

@Override
protected void onResume() {
    super.onResume();

    checkPlayServices();

}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
protected void onPause() {
    super.onPause();

}
@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
            + result.getErrorCode());
}

@Override
public void onConnected(Bundle arg0) {

    displayLocation();


}



private void displayLocation() {
   Log.d("after","clicked");
    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        lblLocation.setText(latitude + ", " + longitude);
        Log.d("lat",String.valueOf(latitude));

    } else {
        Log.d("lat","No lat");

        lblLocation
                .setText("(Couldn't get the location. Make sure location is enabled on the device)");
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

}

}

user3923278
  • 85
  • 1
  • 11
  • Before posting your question you have to take a look in simular questions. Take a look here [link] (http://stackoverflow.com/questions/28877835/android-google-maps-v2-current-position-latitude-longitude-nullpointerexception). you'll find more simular solutions. – BOUTERBIAT Oualid May 20 '16 at 10:31
  • Could you also show what **imports** are their in your class. Or make sure you have Location is enabled in your real device from Settings. – Jay Rathod May 20 '16 at 10:46
  • @jaydroider in my mobile device location is enabled and i have edited the question where u can see the imports – user3923278 May 20 '16 at 10:55
  • If you are using API 23, then you need to enable permission once you install the app. – Parama Sudha May 20 '16 at 11:00
  • Or check whether the location is enabled by manually goes to Setting---> Location Access – Parama Sudha May 20 '16 at 11:02
  • @ParamaSudha i didnot get you can you please elaborate – user3923278 May 20 '16 at 11:02
  • Refer this http://kiddyandroid.blogspot.in/2016/04/getting-latitude-longitude-while.html – Parama Sudha May 20 '16 at 11:03
  • http://www.tutorialsbuzz.com/2016/02/Android-show-Current-Location-On-GoogleMap-Animation.html – Parama Sudha May 20 '16 at 11:07
  • What is the target API Level? – Parama Sudha May 20 '16 at 11:09
  • @ParamaSudha target is 23 – user3923278 May 20 '16 at 11:15
  • May be you need to connect `GoogleApiClient` `onStart` of `Activity`. Your imports looks okay. – Jay Rathod May 20 '16 at 11:18
  • @jaydroider after following your answers and other tutorials i changed my code and still i am not getting my latitude and please have a look at my new code in my edited post inserted at the last as **updated code-----** – user3923278 May 20 '16 at 17:14
  • The `getLastLocation()` may well return null if there's no "last location" available. The method call does not determine the location it only returns it if it's known. And it's only known if some other app has requested a location update recently or since the phone was booted up. (I don't know what's the exact behaviour.) And in any case the "last location" might not even be up-to-date even if it's available. Maybe the documentation should be clearer on this as often people use `getLastLocation()` and then complain that they "can not the get location". – Markus Kauppinen May 20 '16 at 17:29
  • @MarkusKauppinen thank you for sharing your knowledge but can you please tell me what should i write instead of 'getLastLocation()' to get my current location latitude and longitude – user3923278 May 20 '16 at 17:33
  • You could request location updates [as instructed in the documentation](https://developer.android.com/training/location/receive-location-updates.html). If you do not need constant location updates then you can of course stop them as soon as you receive the current location. – Markus Kauppinen May 20 '16 at 17:45

2 Answers2

0

your forgot to call mGoogleApiClient.connect();

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

     private GoogleMap mMap; 
     AppLocationService appLocationService;
     GoogleApiClient mGoogleApiClient;
     private Location mLastLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
            .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
            .addApi(LocationServices.API).build();

 mGoogleApiClient.connect();

}

private void setUpMapIfNeeded() {
    if (mMap == null) {
        mMap = ((SupportMapFragment) 
        getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (mMap != null) {
            displayLocation();
        }
    }
}

private void displayLocation() {

    mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        Log.d("result", latitude + ", " + longitude);

    } else {

      Log.d("result3","(Couldn't get the location. Make sure location is 
      enabled on the device)");
    }
}

@Override
public void onConnected(Bundle bundle) {
          mLastLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
   setUpMapIfNeeded();
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
} 

I have edited your code. See if this work.

Chirag Jain
  • 133
  • 9
  • **D/result3﹕ Couldn't get the location. Make sure location is enabled on the device** this is want i am getting in my logcat – user3923278 May 20 '16 at 10:45
  • please check whether GoogleApiClient is connected or not and also location settings in your mobile settings are enabled – Chirag Jain May 20 '16 at 11:00
  • my location in setting is enabled and can u tell me how to check whether GoogleApiClient is connected or not? – user3923278 May 20 '16 at 11:04
  • mGoogleApiClient.isConnected(); – Chirag Jain May 20 '16 at 13:01
  • after following your answers and other tutorials i changed my code and still i am not getting my latitude and please have a look at my new code in my edited post inserted at the last as **updated code-----** – user3923278 May 20 '16 at 17:14
0

There are 2 mistakes in your code

You are not connected to GoogleApiclient, so call mgoogleApiclient.connect just after you build it using builder.

Call your displayLocation() method in onConnected() callback method. As, this is the success callback of GoogleApiClient, which means you are now connected to the client and can get your location.

Also, You can get location without registering any GoogleApikey until you are not using Maps or Places Api in your app.

Poras Bhardwaj
  • 1,073
  • 1
  • 15
  • 33
  • after following your answer and some other tutorials i changed my code and still i am not getting my latitude and this time my mobile location is also enabled and you can see the new code in my edited post **updated code ------** – user3923278 May 20 '16 at 17:11
  • Can u tell me any other way to fetch the current latitud and longitude – user3923278 May 21 '16 at 12:45
  • Try to debug your code, is GoogleApiClient connected? – Poras Bhardwaj May 23 '16 at 05:57