我想开发一个Android应用程序,它可以计算实际行进距离并在文本视图中显示它。这是我使用的代码,但是当您返回起点时,此代码会减少行进距离。任何人都可以帮助修复此代码,以便它只能累积距离吗?
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
提前致谢。
答案 0 :(得分:0)
请按照以下步骤操作....
第1步:
private Location lastLocation;
private double totalDistance = 0;
第2步:在onCreate()
//Get last location
lastLocation = lm.getLastKnownLocation(lm.GPS_PROVIDER);
第2步:onLocationChanged(位置) //计算距离
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.