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();
}
}
Related
I have an app which calculates distance and speed by gps
the speed is working well
but the distance always equals to zero !!
at first i didn't initialize float[] dist by zero .. but it crashed once gps was found !
that's the code
public class Main_Activity extends Activity {
TextView tvdistance;
TextView tvSpeed;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance = 0;
float[] dist = {
0, 0, 0
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tvdistance = (TextView) findViewById(R.id.tvdistance);
tvSpeed = (TextView) findViewById(R.id.tvspeed1);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
tvdistance.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(LocationManager.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
if (currentLat != 0 && currentLon != 0) {
Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
location.getLongitude(), dist);
distance += (long) dist[0];
}
currentLat = location.getLatitude();
currentLon = location.getLongitude();
float speed = location.getSpeed();
tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
tvdistance.setText("Distance = " + distance);
}
#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
}
};
}
As you have just gotten a location fix, I fully expect the location returned from getLastKnownLocation to be the same as what you get in location. This means that your distance between the two is correctly 0. If you want your older location, you'll need to store that yourself.
Here is the complete code to get location updates from a GPS provider
public class MainActivity extends Activity {
private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
// meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
// second
// Declaring a Location Manager
protected LocationManager locationManager;
// The alert dialog to enable GPS
private Dialog alertDialog;
// flag for GPS status
boolean isGPSEnabled = false;
Location location; // location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
// fetching your current location
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
// Getting current location and adding the marker
locateMe();
}
/**
*
*/
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onResume()
*/
#Override
protected void onResume() {
// Getting location from GPS
super.onResume();
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.e("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
}
Now you can use various methods to store your location. Following are some ways:
Shared preferences
SQLite Database
Web Server
Saving in a file
You can refer this link.
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.
I have an application, which calculate distance after every 100 meters. There is a button and a text view. The button that I used, is an animated button. When I click Button, button spin(Animation Start v.startAnimation(animRotate)). But I need the button animation when acquire the location from GPS.
Here is my activity:
public class Gps extends Activity {
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);
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);
if(lastLat != 0 || lastLon != 0){
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
}
};
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
}
};
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;
}
});
}
}