Get current lat long android - android

I want to get the Location object on Button press.
I know the LocationListener callbacks, however they execute only after a particular time or distance. I want to get Location instantaneously. Are there any methods to do so.

public class GPSHelper {
private Context context;
// flag for GPS Status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
public GPSHelper(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
} public void getMyLocation() {
List<String> providers = locationManager.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = locationManager.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}
}
public boolean isGPSenabled() {
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return (isGPSEnabled || isNetworkEnabled);
}
/**
* Function to get latitude
*/
public double getLatitude() {
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
return longitude;
}

You are welcome to call getLastKnownLocation() on LocationManager to retrieve the last known location for your requested location provider. However:
that location may be old
that location may be null
Hence, your code will need to be able to cope with both of those scenarios.

Use LocationManager class:
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
Log.d("old","lat : "+latitude);
Log.d("old","long : "+longitude);
this.onLocationChanged(location);
}

Try the following:
https://github.com/delight-im/Android-SimpleLocation
If your location is enabled, you need just 3 lines of code:
SimpleLocation location = new SimpleLocation(this); //or context instead of this
double latitude = location.getLatitude();
double longitude = location.getLongitude();

You can get the last known location using FusedLocationProviderClient
There are very simple steps to get current latitude, longitude, altitude & bearing
Update or install Google Play services to the current latest version in your SDK Manager.
Add Location permission into your project's manifest.
Add this line into your Activity/Fragment:
(i) Code For Kotlin
private lateinit var fusedLocationClient: FusedLocationProviderClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
Log.d(TAG, "latitude:" + location?.latitude)
Log.d(TAG, "longitude:" + location?.longitude)
Log.d(TAG, "altitude:" + location?.altitude)
Log.d(TAG, "bearing:" + location?.bearing)
}
(ii) Code for JAVA
private FusedLocationProviderClient fusedLocationClient;
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Log.d(TAG,location.getLatitude)
Log.d(TAG,location.getLongitude)
}
}
});
That's it. Run your code and you can check your current location in Logcat. Don't forget to accept location permission from your emulator or Android phone.
You can not get proper altitude and bearing using FusedLocationProviderClient.
Happy Coding :)

Related

Not getting the location [duplicate]

This question already has an answer here:
getLastKnownLocation method always returns null
(1 answer)
Closed 7 years ago.
I am making a app in which i have to show a splash screen for 1/2 sec.While the splash is loading i have to get the user location.location accuracy is not concern.So for this i have written a code but always i get null from location.
Code
private Context context;
private LocationManager locationManager;
Location location;
double latitude;
double longitude;
public GetLocation(Context context) {
this.context = context;
getLocation();
}
private Location getLocation() {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(getProviderName());
if (location == null) {
locationManager.requestLocationUpdates(getProviderName(), 0, 0, this);
}
return location;
}
String getProviderName() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW); // Chose your desired power consumption level.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // Choose your accuracy requirement.
criteria.setSpeedRequired(true); // Chose if speed for first location fix is required.
criteria.setAltitudeRequired(false); // Choose if you use altitude.
criteria.setBearingRequired(false); // Choose if you use bearing.
criteria.setCostAllowed(false); // Choose if this provider can waste money :-)
// Provide your criteria and flag enabledOnly that tells
// LocationManager only to return active providers.
return locationManager.getBestProvider(criteria, true);
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(context,""+location,Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(context,provider,Toast.LENGTH_LONG).show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Usage
private void getLocation() {
getLocation = new GetLocation(contextActivity);
latitude = getLocation.getLatitude();
longitude = getLocation.getLongitude();
if (latitude != 0 && longitude != 0) {
getLocation.stopUsingGPS();
}
}
Please do help me out.
Thanks.
getLastKnownLocation returns null if a location hasn't been yet acquired. If it is case for your device, the following snippet
if (location == null) {
locationManager.requestLocationUpdates(getProviderName(), 0, 0, this);
}
prevents you from registering the LocationListener, callback for your location manager.
I guess you are not updating location in onLocationChanged. Are you getting location non null object in your toast text?
My answer would be updating location member variable with the location received with onLocationChange event.

Unable to get the correct location within indoor environment using with only WIFI

I wrote a program that provides the user's position with in a building but not the actual position . I Know that Gps does not provide high accurate result with in building . My code is as follows:
public class Internet extends Service implements LocationListener {
Context context;
LocationManager locationManager;
public Internet(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
Location findMeInternet() {
Boolean isInternet = false;
Location location;
isInternet = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isInternet) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 3, 1, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return location;
}
}
return null;
}
//other override methods with empty bodies .
}
Try GPS provider instead of NetWORK provider ,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
Make sure that device GPS is enabled. (If someone needs to downvote, please mention the reason also)

Isn't it possible to get coordinate without wifi?

my code is here:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
It only get coordinate when I connected to internet.
You can use android GPS service to get Longitute and Latitute too,
add the permission in your AndroidMenifest.xml,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Initialization,
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
// This is constructor to get System Location services,
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
Checking if GPS managed to fetch the data,
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

Android GPS using old locations

Im trying to learn more about location services in android and am attempting to build an app which can locate an Android device and send it's latitude and longitude to a server. I've had everything working as expected for a while, but am still being bothered by a small bug. When I send the command from the server to locate the device the first time, the device returns a recent, but old, location such as a road I drove on the same day.
On the second time the device receives a command from the server to locate the device, the device returns an accurate location.
Here is the relevant code:
LocationTracker.java
public class LocationTracker extends Service implements LocationListener {
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10*1000; //10,000 meters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10000; // 10,000 minutes
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
new MyAsyncTask().execute(stringLatitude, stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
//If no GPS, get location from Network Provider
if (isNetworkEnabled && !isGPSEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
Log.i("New Location: ", stringNewLatitude + " " + stringNewLongitude);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public IBinder onBind(Intent intent)
{
return null;
}
Why is my location updating as an old location the first time it tries, and a correct location on the second time?
Also note that I would also like to remove requestLocationUpdates seen here:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
because it causes a handler on dead thread warning, but when I removed it my device stopped acquiring my location. This may be part of the problem.
I would greatly appreciate any help!
It's because you're using getLastKnownLocation().
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) :
Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

onLocationChanged only called once, not update automatically

In android app want to get the location by button click here is my code
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 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;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
public void onLocationChanged(Location location) {
this.location=location;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
and my call function that get the Latitude,Longitude from above code.
double lat = gps.getLatitude();
double log = gps.getLongitude();
but its only give the same location even the place is changed.
any one help me...thanks in advance..
I looked in your code and it seems correct in all way. Can you please try it by making minimum distance to 0 as you have given min. distance 10 meter and may be you didn't moved at that much rate and your service may be taking min. distance as primary point instead of min. time.
#Dynamo: requestupdatelocation call the onLocationChanged callback method. It is not totally depending on the location assignment. location value will change as per the user location updates.
Here question is that "onLocationChanged" callback method is not getting call on given parameter.
Try this
public void onLocationChanged(Location location) {
this.location = location;
}
and also try reducing the MIN_DISTANCE_CHANGE_FOR_UPDATES to a least value.
Your code seems correct. The only reason I could think of is that device is not able to get the locations. It takes a few minutes for the device to get a lock on your location so try giving it some time.
You can use adb shell dumpsys location to check which apps have a location listener registered and if your app is among them. It will also tell you when was the last time android got a location update. Also try running any other location app to see if this problem is with your app or the environment.

Categories

Resources