How to Get the Current Gps Location Programmatically in Android

Get gps location from Android

Try this:

public class MainActivity extends AppCompatActivity {

private Button b;
private TextView t;
private LocationManager locationManager;
private LocationListener listener;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main_activity);

b = (Button) findViewById(R.id.button);
t = (TextView) findViewById(R.id.textView);

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
t.setText(String.valueOf(location.getLongitude()));
}

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

@Override
public void onProviderEnabled(String s) {
//
}

@Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};

b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
configure_button();
}
});
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}

void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this,
ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
request_permission();
}
} else {
// permission has been granted
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
}

private void request_permission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
ACCESS_COARSE_LOCATION)) {

Snackbar.make(findViewById(R.id.main_linear_layout), "Location permission is needed because ...",
Snackbar.LENGTH_LONG)
.setAction("retry", new View.OnClickListener() {
@Override
public void onClick(View view) {
requestPermissions(new String[]{ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 10);
}
})
.show();
} else {
// permission has not been granted yet. Request it directly.
requestPermissions(new String[]{ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 10);
}
}
}

Extract configure_button() to the onClickListener of the button. This way, you only ask for the permission when it is needed (when the button is clicked). It also helps with the case where the user denies permission because clicking the button later in the future will request for the permission again.

There's also a Snackbar with a message telling the user why the permission is needed, along with an action for requesting the permission.

Android :How to get Current Location in Longitude and latitude?

onLocationChanged gets called every time when your location updates , so keep & update a global value and take that value on your Button click to do what you want

 private LatLng latLng;

@Override
public void onLocationChanged(Location location) {
if(location!=null){
latLng = new LatLng(location.getLatitude(), location.getLongitude()); }
}

or based on time or distance you can get the location as well use android.location.LocationListener() see Edit for that,

If you want to manually call onLocationChanged after a time period even the location is not changed use below

 LocationRequest  mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(30000); //5 seconds
mLocationRequest.setFastestInterval(30000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

Edit : This is the location listener you can use this separately without the above if you want

    private LocationManager locationManager;
private android.location.LocationListener myLocationListener;

public void checkLocation() {

String serviceString = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(serviceString);


if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}


myLocationListener = new android.location.LocationListener() {
public void onLocationChanged(Location locationListener) {

if (isGPSEnabled(YourActivityName.this)) {
if (locationListener != null) {
if (ActivityCompat.checkSelfPermission(YourActivityName.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(YourActivityName.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}

if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
} else if (isInternetConnected(YourActivityName.this)) {
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}



}

public void onProviderDisabled(String provider) {

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}
};

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, myLocationListener);
}

isInternetConnected method

public static boolean isInternetConnected(Context ctx) {
ConnectivityManager connectivityMgr = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Check if wifi or mobile network is available or not. If any of them is
// available or connected then it will return true, otherwise false;
if (wifi != null) {
if (wifi.isConnected()) {
return true;
}
}
if (mobile != null) {
if (mobile.isConnected()) {
return true;
}
}
return false;
}

isGpsEnabled method

  public boolean isGPSEnabled(Context mContext) {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

Note : Now do not get confuse. There are 3 ways mentioned here.

1.use onLocationChanged automatically


  1. use onLocationChanged manually

  2. use android.location.LocationListener() added the full implementation (this will not help you to learn but to get a data. Go through these lines and understand them by searching what happen actually )

get the current location fast and once in android

Here, you can use this...

Example usage:

public void foo(Context context) {
// when you need location
// if inside activity context = this;

SingleShotLocationProvider.requestSingleUpdate(context,
new SingleShotLocationProvider.LocationCallback() {
@Override public void onNewLocationAvailable(GPSCoordinates location) {
Log.d("Location", "my location is " + location.toString());
}
});
}

You might want to verify the lat/long are actual values and not 0 or something. If I remember correctly this shouldn't throw an NPE but you might want to verify that.

public class SingleShotLocationProvider {

public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}

// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}

@Override public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override public void onProviderEnabled(String provider) { }
@Override public void onProviderDisabled(String provider) { }
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}

@Override public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override public void onProviderEnabled(String provider) { }
@Override public void onProviderDisabled(String provider) { }
}, null);
}
}
}


// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;

public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}

public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}

How can i get current GPS location ? (not lastknown)

I don't know if you are getting your last location or not. Here's the answer when you are not getting anything at all from the gps provider.

Making this block like this will only make you get your location via gps.

if (gps) {

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 5F, this)

}

The above can return when your device's GPS chipset feels like it's getting signal from the GPS, so when inside a building, it will likely be not getting any responds.
Go outside and try it out.

In your usecase, pressing a button to get an accurate location, in case the user can't receive any signal, you should provide a callback for timeout.

 private val mHandler = Handler(Looper.getMainLooper())

private val mTimeoutRunnable = Runnable {

//stopLoading
//Toast the user to try it somewhere else
}


fun askGsp() {

mHandler.postDelayed(mTimeoutRunnable, 5 * 1000) //time out in 5 seconds

//ask for gps update like the code above
//...
override fun onLocationChanged(location: Location) {

mHandler.removeCallbacks(mTimeoutRunnable) //remove timeout action
locationx.text = location.latitude.toString() +" , "+
location.longitude.toString()
}
}

How can I get the current GPS location?

You Should use GooglePlayServices

compile 'com.google.android.gms:play-services-location:7.0.0'

To get location

 if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}

After connection

public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
@Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}

For more detail information check documentation.

Get user's current location using GPS

Use this class for getting Current Location in your App this is perfectly works for me

/**
* Gps location tracker class
* to get users location and other information related to location
*/
public class GpsLocationTracker extends Service implements LocationListener
{

/**
* context of calling class
*/
private Context mContext;

/**
* flag for gps status
*/
private boolean isGpsEnabled = false;

/**
* flag for network status
*/
private boolean isNetworkEnabled = false;

/**
* flag for gps
*/
private boolean canGetLocation = false;

/**
* location
*/
private Location mLocation;

/**
* latitude
*/
private double mLatitude;

/**
* longitude
*/
private double mLongitude;

/**
* min distance change to get location update
*/
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;

/**
* min time for location update
* 60000 = 1min
*/
private static final long MIN_TIME_FOR_UPDATE = 60000;

/**
* location manager
*/
private LocationManager mLocationManager;


/**
* @param mContext constructor of the class
*/
public GpsLocationTracker(Context mContext) {

this.mContext = mContext;
getLocation();
}


/**
* @return location
*/
public Location getLocation() {

try {

mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGpsEnabled && !isNetworkEnabled) {

/*no location provider enabled*/
} else {

this.canGetLocation = true;

/*getting location from network provider*/
if (isNetworkEnabled) {

mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

if (mLocationManager != null) {

mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (mLocation != null) {

mLatitude = mLocation.getLatitude();

mLongitude = mLocation.getLongitude();
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {

if (mLocation == null) {

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

if (mLocationManager != null) {

mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (mLocation != null) {

mLatitude = mLocation.getLatitude();

mLongitude = mLocation.getLongitude();
}

}
}

}
}
}

} catch (Exception e) {

e.printStackTrace();
}

return mLocation;
}

/**
* call this function to stop using gps in your application
*/
public void stopUsingGps() {

if (mLocationManager != null) {

mLocationManager.removeUpdates(GpsLocationTracker.this);

}
}

/**
* @return latitude
* <p/>
* function to get latitude
*/
public double getLatitude() {

if (mLocation != null) {

mLatitude = mLocation.getLatitude();
}
return mLatitude;
}

/**
* @return longitude
* function to get longitude
*/
public double getLongitude() {

if (mLocation != null) {

mLongitude = mLocation.getLongitude();

}

return mLongitude;
}

/**
* @return to check gps or wifi is enabled or not
*/
public boolean canGetLocation() {

return this.canGetLocation;
}

/**
* function to prompt user to open
* settings to enable gps
*/
public void showSettingsAlert() {

AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.AppTheme));

mAlertDialog.setTitle("Gps Disabled");

mAlertDialog.setMessage("gps is not enabled . do you want to enable ?");

mAlertDialog.setPositiveButton("settings", new OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent mIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(mIntent);
}
});

mAlertDialog.setNegativeButton("cancle", new OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();

}
});

final AlertDialog mcreateDialog = mAlertDialog.create();
mcreateDialog.show();
}

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}

public void onLocationChanged(Location location) {
// TODO Auto-generated method stub

}

public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub

}

}

& Use it this way

GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(YourActivity.this);

/**
* Set GPS Location fetched address
*/
if (mGpsLocationTracker.canGetLocation())
{
latitude = mGpsLocationTracker.getLatitude();
longitude = mGpsLocationTracker.getLongitude();
Log.i(TAG, String.format("latitude: %s", latitude));
Log.i(TAG, String.format("longitude: %s", longitude));

}
else
{
mGpsLocationTracker.showSettingsAlert();
}

& don't forget to set permission in Manifest.xml

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

How to get the current location latitude and longitude in android

Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation

Demo

AndroidManifest.xml

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

Activity

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView textview;

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

// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);

if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView)findViewById(R.id.fieldLatitude);
textview.setText(stringLatitude);

String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView)findViewById(R.id.fieldLongitude);
textview.setText(stringLongitude);

String country = gpsTracker.getCountryName(this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText(country);

String city = gpsTracker.getLocality(this);
textview = (TextView)findViewById(R.id.fieldCity);
textview.setText(city);

String postalCode = gpsTracker.getPostalCode(this);
textview = (TextView)findViewById(R.id.fieldPostalCode);
textview.setText(postalCode);

String addressLine = gpsTracker.getAddressLine(this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText(addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
return true;
}
}

GPS Tracker

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
* Create this Class from tutorial :
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
*
* For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
*
*/

public class GPSTracker extends Service implements LocationListener {

// Get Class Name
private static String TAG = GPSTracker.class.getName();

private final Context mContext;

// flag for GPS Status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;

Location location;
double latitude;
double longitude;

// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;

// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;

public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}

/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {

try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;

Log.d(TAG, "Application use GPS Service");

/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/

provider_info = LocationManager.GPS_PROVIDER;

} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;

Log.d(TAG, "Application use Network State to get GPS coordinates");

/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;

}

// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);

if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}

/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}

/**
* GPSTracker latitude getter and setter
* @retu

Related Topics



Leave a reply



Submit