Finding current location of the user in Android
I am new to Android and I am trying to develop an Android app which shows current location of the user. I am using Genymotion. Now I am using
mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
to get the last location of the device. The thing is I wanted to get the current location but with this I get mlocation
as not null that's fine. But in the map it shows last location of the device always not the current location.
code snippet
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "inside onconnected Location services connected");
Location mLocation=null;
mLocationRequest= new LocationRequest();
mLocationRequest.setInterval(10 * 1000) ;
mLocationRequest.setFastestInterval(1 * 1000);mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
}
mLocation=LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
if(mLocation==null)
{
Log.d("***Inside mlocation***", "***mlocation is null here");
}
if (mLocation != null) {
onLocationChanged(mLocation);
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleClient, mLocationRequest, this);
}
@Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude,currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Im here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
and in onstart()
I called googleapi.connect()
and I used setUpMapIfNeeded()
appropriately.
Please tell me whats the problem in this code. I am trying this for 3 days.
Solution 1:
posting simple solution with code.
add permissions inside AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
if you app is marshmallow compatible then check run time permission.
add dependency inside gradle file:
compile 'com.google.android.gms:play-services:9.2.0'
implements this two interface in you activity
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
and
create googleapiclient object like this in oncreate:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
and make this on start activity
mGoogleApiClient.connect();
here we go on result callback of location on this override method.
public void onConnected(@Nullable Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
} else {
Toast.makeText(getApplicationContext(), "Your Location Not Found", Toast.LENGTH_LONG).show();
}
}
full code of activity is something like that:
public class LocationActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = LocationActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
@Override
protected void onStart() {
// connect googleapiclient
mGoogleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
// disconnect googleapiclient
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// here we go you can see current lat long.
Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}}
p.s. googleapiclient is not working in emulator without play services, so you have to test it on real devices. please make sure gps is enable on that device.
if you want to use traditional method for get location then try this tutorial. http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
------UPDATE JUNE 15---------
for latest apis check android google post: https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html