我有一个简单的应用程序启动gps方法来获取经度和纬度来使用位置测量距离,并将结果添加到总距离变量以给出总行程。
但是在跑步期间,总行程不规则地从0m到6000m不等。
这是我的代码。
public void geoloc_start() {
// Acquire a reference to the system Location Manager
loc_man = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
loc_list = new LocationListener() {
// Called when a new location is found by the network location provider.
public void onLocationChanged(Location geo_loc) {
newLongitude = geo_loc.getLongitude();
newLatitude = geo_loc.getLatitude();
Location new_location = new Location("Point A");
new_location.setLatitude(newLatitude);
new_location.setLongitude(newLongitude);
Location old_location = new Location("Point B");
old_location.setLatitude(oldLatitude);
old_location.setLongitude(oldLongitude);
distance = old_location.distanceTo(new_location);
tot_distance += distance;
oldLatitude = newLatitude;
oldLongitude = newLongitude;
//************************ Round coordinates to 5 dec places + set them to string to display ************************//
newLongitude = Math.round(newLongitude * 100000);
newLatitude = Math.round(newLatitude * 100000);
tot_distance = Math.round(distance * 1000);
newLatitude = newLatitude / 100000;
newLongitude = newLongitude / 100000;
tot_distance = tot_distance / 1000;
latitude_text = Double.valueOf(newLatitude).toString();
longitude_text = Double.valueOf(newLongitude).toString();
distance_text = Double.valueOf(tot_distance).toString();
//*******************************************************************************************************************//
geoLat.setText("Lat: " + latitude_text);
geoLong.setText("Long: " + longitude_text);
geoDist.setText("Dist: " + distance_text + "m");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
loc_man.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, loc_list);
}
/******************************************* STOP GPS FUNCTION *******************************************/
private void geoloc_stop() {
loc_man.removeUpdates(loc_list);
loc_man = null;
geoLat.setText("Lat: 0");
geoLong.setText("Long: 0");
geoDist.setText("Dist: 0m");
tot_distance = 0;
}