Android GPS distance ZERO, when walking back to start position [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an android application which calculate distance from GPS while walking. When I start application and go straight it gives the correct distance but when I back to the starting point it distance decreases. Finally it shows 0, when I reach to the original position.
So, my question is how can I calculate distance perfectly of my every step.
Here is my activity:
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Location loc;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Log.e("successss", "111111111111");
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("successss", "2222222222222");
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get last location
if(!doubleclick){
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
Log.e("successss", "33333333333333333");
if (loc == null) {
display.setText("No GPS location found");
} else {
Log.e("successss", "444444444444");
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
Log.e("successss", "5555555555555");
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
Log.e("successss", "66666666666");
Log.e("Location", "lastLat:" + lastLat);
Log.e("Location", "currentLat:" + currentLat);
//Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
//lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc2.getLatitude();
currentLon = loc2.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Please help me. Thank you.

Your problem is here:
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
The Location.distanceTo(Location) method is calculating the distance in meters. %.2f will only show 2 digits after the comma and cuts the last digit. Because 1 meter / 1000f = 0.001 km. That's why you will never see the 3rd digit in your TextView. The result for distances < 10 meters will be shown as 0.00.

I may be mistaken (I haven't really dug into your code) but could it be as simple as this:
It sounds like you're continuously calculating the distance from some point x = (0, 0). Of course, when you return towards x, the distance from it will decrease.
Simple solution:
Separate the distance calculated for each "step" from the total distance
For every time you calculate the distance, reset the starting point (move X to your current position), and add the new distance to a total.

Related

Calculate traveled distance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to develop an android app which can calculate the actual distance traveled and show it in a text view. Here is the code I used but this code decreases the traveled distance when you heading back to the start point. Can anyone help to fix this code so it can accumulate distances only?
display = (TextView) findViewById(R.id.info);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
//set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
//Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//set Current latitude and longitude
currentLon=loc.getLongitude();
currentLat=loc.getLatitude();
// TODO Auto-generated method stub
//start location manager
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
//Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
//Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km",distanceKm ));
Location locationC = new Location("point c");
locationA.setLatitude(currentLat);
locationA.setLongitude(currentLon);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Thanks in advance.
Follow these steps....
Step 1 :
private Location lastLocation;
private double totalDistance = 0;
Step 2 : In onCreate()
//Get last location
lastLocation = lm.getLastKnownLocation(lm.GPS_PROVIDER);
Step 2 : onLocationChanged(location)
// calculate distance
double distanceMeters = lastLocation.distanceTo(location);
double distanceKm = distanceMeters / 1000f;
// when the location change keep updating the total distance
totalDistance += distanceKm;
lastLocation = location; // assign the current location to lastLocation.

android gps distance shows previous record while restart

I have an android application which calculate distance from GPS while walking. First time distance calculation correct. But when I restart application, it shows the previous distance initially, it should be 0.
Here is my activity:
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Please help me. It is very important to me.
Edited Code
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
Animation animRotate;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Log.e("successss", "111111111111");
}
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
// in.putExtra("distance", display.toString());
startActivity(in);
finish();
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("successss", "2222222222222");
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get last location
if(!doubleclick){
Location loc1 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
Log.e("successss", "33333333333333333");
if (loc1 == null) {
display.setText("No GPS location found");
} else {
Log.e("successss", "444444444444");
// set Current latitude and longitude
currentLon = loc1.getLongitude();
currentLat = loc1.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
Log.e("successss", "5555555555555");
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
Log.e("successss", "66666666666");
Log.e("Location", "lastLat:" + lastLat);
Log.e("Location", "currentLat:" + currentLat);
//Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
//lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc2.getLatitude();
currentLon = loc2.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
if (lastLat != 0 || lastLon != 0) {
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
Constant.distance = (String.format("%.2f Km", distanceKm));
start.startAnimation(animRotate);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Because you use:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
set it to null if you want to wait for actual position. then start your jobs from OnLocationChangedListener
that method retreives the last position of the user... GPS takes some time to get the actual position.
EDIT
remove this code from the else:
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
and just wait for the position instead..display a toast for example, telling the user that you are waiting for the position.
then, when you have the position, do this stuff in the
public void onLocationChanged(Location location) {}
method..
I don't know what you're code exactly do...I'm just trying to explain you how I would to this..you have to wait and don't start your operations at the creation of the view, but you have to start everything when you have the position
when you restart your app, it takes some time for the GPS to get the new location coordinates.
in your code you have this
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
so, loc is having the lastKnownLocationValues from the last run and hence displaying them.
if you dont want to display the last known location values, assign loc = null on every restart, but then it will take some time to fetch the first location.
this peculiar behavior is implemented because generally it may happen that your GPS connectivity is lost for a few moments, in that short span you don't want to show the user that the location is null or could not be found, because probably in this small span they haven't travelled too far, and so you display the last known location instead.
EDIT:
remove this code from your else
and do this is your locationListener
instead of
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
Log.e("Location", "currentLat:" + currentLat);
}
// Set the last latitude and longitude
startStop.setText("Stop");
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
}
change to
if (!enabled) {
Intent inte = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(inte);
} else {
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0,
Loclist);
display.setText("searching for location...");
}
and then update your textboxes in your locationListener's onLocationChanged() method
EDIT:
declare two more variables and a flag
private boolean enabled;
double currentLon = 0;
double currentLat = 0;
double prevLon = 0;
double prevLat = 0;
bool firstTime = true;
in your onLocationChanged()
public void onLocationChanged(Location location) {
if(!firstTime){
prevLon = currentLon;
prevLat = currentLat;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(prevLat);
locationA.setLongitude(prevLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
...
}
else{
firstTime = false;
currentLat = location.getLatitude();
currentLon = location.getLongitude();
}
}

Android: How to Calculate distance Travelled using GPS

I have an application, which calculated distance after every 100 meters. There is a button and a text view. When I click the button, the calculated distance after every 100 meters and shows it on the text view. But I found a bug. When I lunch the application first time, the text view should 0.0km but initially it shows 75000km. I don't know why. Please help me. It is very important to me.
I have one more question, the button that I used, is an animated button. When I click Button, button spin(Animation Start v.startAnimation(animRotate)). I need the animation when acquire the location. Where I have to put the animation (v.startAnimation(animRotate)).
Here is my activity:
public class Gps extends Activity {
TextView display;
Button start;
boolean doubleclick = false;
AnimationDrawable AppNameAnimation;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance;
TextView startStop;
LocationManager lm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
startStop = (TextView) findViewById(R.id.textView2);
display = (TextView) findViewById(R.id.textView1);
start = (Button) findViewById(R.id.button1);
final Animation animRotate = AnimationUtils.loadAnimation(this,
R.anim.anim_rotate);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!doubleclick) {
v.startAnimation(animRotate);
startStop.setText("Stop");
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if (loc == null) {
display.setText("No GPS location found");
} else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
// Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
doubleclick = true;
} else {
lm.removeUpdates(Loclist);
startStop.setText("Start");
v.clearAnimation();
doubleclick = false;
Intent in = new Intent(Gps.this, NextActivity.class);
startActivity(in);
}
}
});
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km", distanceKm));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};

Android GPS: measured distance between locations continiously

I want to create an application of distance tracker in android. I have a Spinner, button and a TextView.Initially text view will be 0.00km.When I click the button (GPS tracking start) and start walking in the text view it will show the distance continuously. When I click the button again(GPS tracking terminate) and show the full distance between clicking button.
Here is the screenshot that the application will look like:
Here is My Code:
public class Gps extends Activity {
TextView display;
double currentLon=0 ;
double currentLat=0 ;
double lastLon = 0;
double lastLat = 0;
double distance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
display = (TextView) findViewById(R.id.textView1);
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
if(loc==null){
display.setText("No GPS location found");
}
else{
//set Current latitude and longitude
currentLon=loc.getLongitude();
currentLat=loc.getLatitude();
}
//Set the last latitude and longitude
lastLat=currentLat;
lastLon=currentLon ;
}
LocationListener Loclist = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//start location manager
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
//Get last location
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
//Get new location
Location loc2 = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
double distanceMeters = locationA.distanceTo(locationB);
double distanceKm = distanceMeters / 1000f;
display.setText(String.format("%.2f Km",distanceKm ));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
Please help me. Thanks.
You should register a listener on the GPS when the location changed. You basically have to store the previous known location and compare it with the new one.
The simplest way to get the distance between two points would be to use:
sqrt( (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 )
X may be the latitude
Y may be the longitude
Z may be the altitude
Here is a pseudo code sample to help you
public class GpsCalculator
{
private LocationManager locationManager = null;
private Location previousLocation = null;
private double totalDistance = 0D;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minutes
public void run(Context context)
{
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
// Add new listeners with the given params
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Network location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Gps location
}
public void stop()
{
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location newLocation)
{
if (previousLocation != null)
{
double latitude = newLocation.getLatitude() + previousLocation.getLatitude();
latitude *= latitude;
double longitude = newLocation.getLongitude() + previousLocation.getLongitude();
longitude *= longitude;
double altitude = newLocation.getAltitude() + previousLocation.getAltitude();
altitude *= altitude;
GpsCalculator.this.totalDistance += Math.sqrt(latitude + longitude + altitude);
}
// Update stored location
GpsCalculator.this.previousLocation = newLocation;
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
}
And the Activty should look like that:
public class MainActivity extends Activity
{
private Button mainButton = null;
private boolean isButtonPressed = false;
private GpsCalculator gpsCalculator = null;
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
// Create a new GpsCalculator instance
this.gpsCalculator = new GpsCalculator();
// Get your layout + buttons
this.mainButton = (Button) findViewById(R.id.main_button);
this.mainButton.addOnClickListener(new OnClickListener() {
#Override
public void onClick()
{
// Enable or diable gps
if (MainActivity.this.isButtonPressed) gpsCalculator.run(this);
else gpsCalculator.stop();
// Change button state
MainActivity.this.isButtonPressed = !MainActivity.this.isButtonPressed;
}
});
}
}

Android:GPS distance measure - not counted correctly kilometers

I have one app which count the traveled km. but when I am driving with my car in the first 1 or 2 km. everything is fine and after that my app get slow.For example when I am traveled 2km. my app is 1.93 or when I am traveled 70km. my app is 48km.
And I have another little problem.
When I started first time the app,I get big value (for example 5536km.) and when I restarted the program I get normal value 0.0km.This is just when i get started the first time GPS if I turned off GPS and after that turned on I will get again the same problem.
Sorry for my bad english.
Thanks in advance.
public class Gps extends Activity {
TextView display;
double km;
double currentLon=0 ;
double currentLat=0 ;
double lastLon = 0;
double lastLat = 0;
double distance;
double distanceMeters;
double distanceKm;
double distanceKm1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
display = (TextView) findViewById(R.id.info);
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
Location loc = lm.getLastKnownLocation(lm.GPS_PROVIDER);
display.setText("GPS not found");
if(loc==null){
display.setText("GPS not found");
}
else{
//Get the last latitude and longitude
lastLon=loc.getLongitude();
lastLat=loc.getLatitude();
}
}
LocationListener Loclist = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//start location manager
LocationManager lm =(LocationManager) getSystemService(LOCATION_SERVICE);
//Get last location
location = lm.getLastKnownLocation(lm.GPS_PROVIDER);
//Request new location
lm.requestLocationUpdates(lm.GPS_PROVIDER, 0,0, Loclist);
//get the current lat and long
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Location locationA = new Location("point A");
locationA.setLatitude(lastLat);
locationA.setLongitude(lastLon);
Location locationB = new Location("point B");
locationB.setLatitude(currentLat);
locationB.setLongitude(currentLon);
distanceMeters = locationA.distanceTo(locationB);
distanceKm = distanceMeters / 1000f;
display.setText(String.format("traveled km.\n%.2f km.",distanceKm));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
I can answer your second question:
When I started first time the app,I get big value (for example
5536km.)
This is the distance from (0,0) (aequator) to your current location.
It seems that lastLon and lastLat have the initial value of 0.
So you must avoid that lastLon and lastLat is invalid.
Explicitly check for not imnitialized.

Categories

Resources