User's location not correct - java

I'm trying to get the user's current location for my weather application but i get the location of some "US" area. I've tried multiples tutorials but failed to get the correct current location.
It returns me:
latitude: 37.421998333333335
longitude: -122.08400000000002
The location is "Mountain View,CA,US"
The code I've used is below:
GpsTracker.java
public class GpsTracker implements LocationListener {
Context context;
public GpsTracker(Context c)
{
context = c;
}
public Location getLocation()
{
if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(context,"Permission not granted",Toast.LENGTH_SHORT).show();
return null;
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(isGpsEnabled)
{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return l;
}
else{
Toast.makeText(context,"Enable GPS",Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
In my main class I'm getting the location like this:
public void getLocation()
{
gpsTracker = new GpsTracker(getApplicationContext());
Location l = gpsTracker.getLocation();
if(l != null)
{
lat = l.getLatitude();
lon = l.getLongitude();
}
Log.d("User's location","Latitude"+lat);
Log.d("User's location","Longitude"+lon);
}

The Location that you need is returned in the method onLocationChanged.
So you could assign it to a variable and then return it:
private Location lastLocation;
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
}
public Location getLastLocation() {
return lastLocation;
}
Call requestLocationUpdates in the onCreate of your activity and then call getLastLocation when you need to show it.
Or you can implement a callback to notify the activity when the location changes.

You are probably getting the last known location and using that tool is probably handing back this address. Consider using a better tool or just FusedLocationProviderClient. However, I like SmartLocation library personally.
https://github.com/mrmans0n/smart-location-lib
It gives fallback providers in the event of one unavailable. There is a little learning curve to use the library, but once you implement it, it works nicely.

Related

Any code for updating the distance when my current location is moved in google map

I can find the distance between the current location and the nearby place but I can't update the distance when I'm moving. Is there any code to update the distance?
you can use the LocationListener
public class mLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// add your code here to run when location changed
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
you can set when to execute the code by either time limit or a minimum distance
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationListener listener= new mLocationListener ();
if (locationManager != null) {
locationManager .requestLocationUpdates(LocationManager.GPS_PROVIDER, mintime, mindistance, listener);
}
for more details Visit https://developer.android.com/reference/android/location/LocationListener
Update : mintime should be long and mindistance should be float
about request location function
https://developer.android.com/reference/android/location/LocationManager#requestLocationUpdates(java.lang.String,%20long,%20float,%20android.location.LocationListener)

Get location updates using location callbacks

I'm trying to get the user location using FusedLocationProviderClient as follows:
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, null);
I get location updates in this location calls
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for (Location location : locationResult.getLocations()) {
// list of locations
}
}
};
I read that locationResult.getLocations() retrieves a list of location objects ordered from oldest to newest,
I couldn't understand that all I want is to get the user location at the moment.
Any help regarding this?
You can use locationResult.getLastLocation() to get the most up to date location available.
From the docs: LocationResult.getLastLocation()
public Location getLastLocation ()
Returns the most recent location
available in this result, or null if no
locations are available.
You could use LocationManager instead of FusedLocationProviderClient. It could be more easier.
LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Current location", location.toString());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
//Checks permission
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;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
This will give you location when user moves.

(Android) Get latitude and longitude, always zero

I have an issue, I need to get the latitude and longitude of one specific moment like taking a picture. I get the Double values, the problem is that they're always 0. I receive no exceptions, and the coordinates are uploaded successfully to Firebase Database, but when I check them in the JSON, they are always zero (I took like 20 pictures).
This is my sections code of "location" stuffs and the uploading to Firebase Database.
My Main Activity is like this.
public class MainActivity extends AppCompatActivity implements LocationListener
Global variables related to Location
double latitude;
double longitude;
This goes inside onCreate():
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
final Location location= new Location(networkProvider);
onLocationChanged(location);{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(gpsProvider, 5000, 10, this);
This goes in a button onClickListener(), also inside onCreate() method.
//Insert coordinates to JSON Firebase database...
Coordinates coordinates = new Coordinates();
coordinates.setLatitude(location.getLatitude());
coordinates.setLongitude(location.getLongitude());
testReference.push().setValue(coordinates);
Toast.makeText(MainActivity.this, "Coordinates uploaded!", Toast.LENGTH_LONG).show();
Also I have these methods inside MainActivity:
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
Try this:
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
if(providerName!=null)
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
and Implement Your Location Listener class:
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
location = loc;
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) {
}
}
check null value for getLastKnownLocation() method..

GPS Location on Button Press

I am currently writing an app which will access the current location on the press of a button, and print it out. What I have right now is a method which gets the last known location. I have seen in many places that one is to implement a class that gets the location. My current code returns it as a string, but it only gets the location that was last updated by the phone. How can I change this so that when I press the button and call a method that uses this String, it will get the currentLocation rather than the lastLocation?
Thank you so much!
Also, This is my first ever android app, and I only have intermediate knowledge of Java and class implementation.
public String getLocation(){
String userLocation;
try {
LocationManager locMgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String userLocator = recentLoc.toString();
userLocation = compressString(userLocator);
//userLocation = recentLoc.toString();
}
catch(Exception e) {
userLocation = "Location failed";
}
return userLocation;
}
I think your GPS is turned off right now. If you turn on your device's location services, it will print out the last location which is near by you. If it won't work, you must implement LocationListener class to your activity. Like at this link.
Try with this code:
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
double lat=location.getLatitude();
double lng=location.getLongitude();
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//or LocationManager.NETWORK_PROVIDER
}
Try this in onClick method
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
}

Android onLocationChanged and MainActivity class

I have the following code:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
and in my MainActivity
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Now, all I want is to receive the current position of the device ONCE to the MainActivity class (get altitude and longitude variables to use later in the application).
A. how do I stop receiving the location after a single time? The function lm.removeUpdates(listener) can only be called in the MainActivity class.
B. basically the same. How do I connect between the MyLocationListener class and the MainActivity one?
Sorry, I'm a newbie to Android and Java development.
And thanks!
You may use the following sample code:
public class LocationGetter {
private final Context context;
private Location location = null;
private final Cordinate gotLocationLock = new Cordinate();
private final LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
synchronized (gotLocationLock) {
LocationGetter.this.location = location;
gotLocationLock.notifyAll();
Looper.myLooper().quit();
}
}
};
public LocationGetter(Context context) {
if (context == null)
throw new IllegalArgumentException("context == null");
this.context = context;
}
public void getLocation(int maxWaitingTime, int updateTimeout) {
try {
final int updateTimeoutPar = updateTimeout;
synchronized (gotLocationLock) {
new Thread() {
public void run() {
Looper.prepare();
LocationResolver locationResolver = new LocationResolver();
locationResolver.prepare();
locationResolver.getLocation(context, locationResult, updateTimeoutPar);
Looper.loop();
}
}.start();
gotLocationLock.wait(maxWaitingTime);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
gteAddress ();
}
public double getLatitude() {
return location.getLatitude();
}
public double getLongitude() {
return location.getLongitude();
}
In your activity use:
_locationGetter=new LocationGetter(context);
_locationGetter.getLocation(200000000, 10000000);
_locationGetter.getLongitude();
_locationGetter.getLatitude();
You can also use LocationManager.removeUpdates after obtining the coordinates (and possibly checking if the coordinates are sufficient for your needs):
#Override
public void onLocationChanged(Location loc) {
// called when the listener is notified with a location update from the GPS
Log.d("Latitude", Double.toString(loc.getLatitude()));
Log.d("Longitude", Double.toString(loc.getLongitude()));
lm.removeUpdates(this);
}

Categories