LocationManager minDistance - android

My sample code:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 50.0f, this);
. . .
public void onLocationChanged(Location loc) {
System.out.println(loc.getLatitude()+ " - " + loc.getLongitude());
}
my minDistance parameter set to 50.0f (50 metres)
but onLocationChanged called many times even if I dont move phone at all.
As I found from docs:
The minDistance parameter can also be used to control the frequency of
location updates. If it is greater than 0 then the location provider
will only send your application an update when the location has
changed by at least minDistance meters.
so my question is why location changed ?

Related

How to get current latitude and longitude and show in a toast?

Hello I know this question is already existed but not getting my solution till now . I have tried many methods to get current location in android studio using java but all are showing the same message location is null and latitude longitude are showing 0.0/0.0
Kindly if any body knows the perfect solution to fix this problem ?
You can use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(this, "longitude " + longitude + "latitude " + latitude, Toast.LENGTH_SHORT).show();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You can add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

Android: Issue in calculating distance using Location manager

Currently I am working on an application, where I want to calculate distance a vehicle travels. My requirement is while driving car, my Android device should calculate total distance I traveled and send this information to server. In order to do this, I used Android's location manager api, set criteria and used getBestProvider. This way we can either use GPS or Network to get latitude and longitude. The following is the code snippet of this:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider,30000,5, this);
onLocationChanged() call back method provide latitude and longitude every time. We always store previous coordinates and when we get new coordinates we find the distance between the two using distanceBetween() api. The following is the code snippet of this:
public void onLocationChanged(Location location) {
findLatLongDistance(location);
}
private void findLatLongDistance(Location location) {
// TODO Auto-generated method stub
try{
Date date = new Date();
TimeStamp2 = sdf.format(date);
getSavedLatLong();//get lat and long from preference
Location locationB = new Location("point B");
locationB.setLatitude(location.getLatitude());
locationB.setLongitude(location.getLongitude());
Location locationA = new Location("point A");
locationA.setLatitude(prelat_val); //lat from pref locationA.setLongitude(prelong_val); //long from pref
if(prelat_val>0.0 && prelong_val>0.0){
Toast.makeText(LocationService.this,"Location Odometer Sum "+odometer_sum, Toast.LENGTH_LONG).show();
float distance2 = getDistance(prelat_val,prelong_val,location.getLatitude(),location.getLongitude());
odometer_sum = odometer_sum + (distance2/1000);
Toast.makeText(LocationService.this,"Lat "+prelat_val+"Long "+prelong_val+"Sum "+odometer_sum, Toast.LENGTH_LONG).show();
}
saveData(lat,lng,odometer_sum);
}catch(Exception e){
e.printStackTrace();
}
}
public float getDistance(double d, double e, double f, double g) {
float [] dist = new float[2];
Location.distanceBetween(d,e,f, g, dist);
return dist[0] ;
}
This is the list of issue that we face here:
The location it provide is not accurate. There is a difference of about 300-400 metres while we testing this app in 5 km distance
When the mobile is in same location for long time, it always provide different latitude and longitude. If you check above code snippet, in requestLocationUpdates(), we are setting 30 seconds time interval and 5m distance. Here what we thought is, if my mobile device move 5m distance AND if it cross 30 seconds interval, it will provide new latitude and longitude. But what really happens is, it provide coordinates every 30 seconds irrespective of device movement. I am not sure how to fix this issue.
While device is moving, how to get accurate value. Do I need to do some more things in the code?
I really spend so many hours trying various options. But I feel I am missing something here. Please help me on this. Thanks in advance..
Thanks,
Your minTime value in requestLocationUpdates() is 30seconds. Thats too long for an app that tries to calculate accurate distances. I have used locationManager.requestLocationUpdates(provider, 0, 5, locationListener);
in my code for long and I get accurate updates. Though this drains the battery very fast. So you would have to try different values to strike a balance between accuracy and battery life and see what suits your app

How do I switch providers after waiting for 'x' amount of time when attempting to retrieve a location fix?

I am building a GPS Android application whereby it retrieves the nearest places based on the user's current location. At first, I detect both GPS and network to see if they are enabled. If both are enabled I would use GPS first because it is the most accurate, and for my application it is safe to assume they are outside, therefore, retrieving GPS should not take too long. Nevertheless, there are always situations when GPS takes a long time. How do I therefore implement a way to switch over to NETWORK_PROVIDER if GPS takes over, for example, 2 minutes?
This is my code right now:
I check if GPS or internet is enabled.
if(!GPSEnabled && !networkEnabled)
{
Toast.makeText(this, "Error: This application requires a GPS or network connection",
Toast.LENGTH_SHORT).show();
}
else
{
if(GPSEnabled)
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else if(networkEnabled)
{
System.out.println("Getting updates from network provider");
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
This is the onLocationChanged method. I get the lat/lng values and then send them off to my server and then do appropriate stuff with it.
public void onLocationChanged(Location location)
{
//Get coordinates
double lat = (location.getLatitude());
double lng = (location.getLongitude());
Log.d("MainActivity", "got location: " + lat + ": " + lng);
//get nearest locations
new GetLocations().execute(SharedVariables.root + SharedVariables.locationsController + SharedVariables.getNearestMethod + lat + "/" + lng);
// Zoom in, animating the camera after the markers have been placed
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
System.out.println("lat = " + lat + ", lng = " + lng);
//Stop listening for updates. We only want to do this once.
locManager.removeUpdates(this);
}
What would I need to add to switch over to Network or GPS if either one takes too long?
I'd recommend to use both providers at the same time and determine more accurate location using, for example, isBetterLocation() function from this article: http://developer.android.com/guide/topics/location/strategies.html. In this case users won't have to wait 2 minutes to use your app, if GPS is slow. At first, you'll use network updates, and then, when GPS fixes are obtained, more accurate locations.

Distance senstivitiy of onLocationChanged()

I am a newbie with java and android. I managed to follow some tutorials to get my gps to work on an android 2.3 phone, but i notice the phone's gps is only accurate within 40 meters, which correpsonds to an accuracy of the third decimal place in latitude/longitude.
My debug log shows this change(while im sitting on my laptop, typing)
LOCATION CHANGED(2137): 43.522701025009155
LOCATION CHANGED(2137): -72.13161981105804
LOCATION CHANGED(2137): 43.522695660591125
LOCATION CHANGED(2137): -72.13161981105804
This is my code
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
else{
// Log.v(TAG,"LOCATION not found");
}
// Log.d("LOCATION is", location.getLatitude() + "");
}
Is it possible to change the onLocationChanged() function to something like
public void onLocationChanged(Location location, minimumdistance_changed)
where minimumdistance_changed is the accuracy of the current accuracy of gps. I'll also be happy with just setting the minimumdistance_changed value to 100meters as long as it will mean i only get a reading from onLocationChanged when the gps value changes to the third decimal place.
Upon requesting location updates from the location manager you can specify a minimum distance between updates:
lm.requestLocationUpdates(provider, timeBetweenUpdates, distBetweenUpdates, listener);
But is is only a hint, the system is not required to follow your hint.

Android: Not able to get accurate latitude and longitude value

In my application I want latitude and longitude value by GPS and/ or Network. My code work but some time it give accurate value some time it not give the accurate value, some time it give the value which is 10 or 20 meter far from the accurate place.
Code:
mlocListener = new MyLocationListener(getApplicationContext());
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
10000, 0, mlocListener);
} else if (mlocManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 10000, 0, mlocListener);
}
Location gpsLocation = mlocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location netLocation = mlocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null) {
mlocListener.latitude = gpsLocation.getLatitude();
mlocListener.longitude = gpsLocation.getLongitude();
double lat = (double) (gpsLocation.getLatitude());
double lng = (double) (gpsLocation.getLongitude());
Toast.makeText(this, "Location attributes using GPS Provider",
Toast.LENGTH_LONG).show();
} else if (netLocation != null) {
mlocListener.latitude = netLocation.getLatitude();
mlocListener.longitude = netLocation.getLongitude();
double lat = (double) (netLocation.getLatitude());
double lng = (double) (netLocation.getLongitude());
Toast.makeText(this, "Location attributes using NETWORK Provider",
Toast.LENGTH_SHORT).show();
}
Use loc.getAccuracy() method to check the accuracy level of location you received. If the value is less then 10(or less than that) then you can consider it , otherwise wait for location Lister to fetch another location.
getLastKnownLocation is your last known location, dont use just getAccuracy also check the time.
Better dont use getLastKnownLocation if you need only accurate location.
Usually GPS is accurate upto 3m but if its 10 to 20 meters, it is something possible with GPS.
A standard GPS receiver for civil use offers an accuracy down to a few
meters. In praxis the number and geometry of the received satellites
influences the accuracy considerably, and in daily use, accuracies of
about 20 m can be expected.
GPS Accuracy
Also if you are getting your current location from network provider, you may expect even more inaccurate locations.
If you are looking forward to get maximum accuracy, I will say that you dismiss network provider because it is influenced by other factors related to phone operator etc.
locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
This get your location using your phone internal GPSreceiver (time costly) but it gives you the maximum possible accuracy.

Categories

Resources