计算使用位置管理器运行的Android距离

时间:2017-01-18 14:45:21

标签: android

我目前正在制作一个简单的健身应用程序,允许用户跟踪他/她的表现(跑步,走路)。我一直在使用位置管理器来获得非常好的移动速度。但是我需要获得行进的距离,如何使用位置管理器(长和纬度)来获得距离?

由于

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_track);

    start = (Button) findViewById(R.id.btnStart);
    speed = (TextView) findViewById(R.id.txtSpeed);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);


    //initialize location listener
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            getSpeed(location);
            double lat2 = location.getLatitude();
            double lng2 = location.getLongitude();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
        }

        //get the speed from the given location updates
        public void getSpeed(Location location) {
            currentSpeed = (location.getSpeed() * 3600 / 1000);
            String convertedSpeed = String.format("%.2f", currentSpeed);
            speed.setText(convertedSpeed + "Km/h");
        }
    };

1 个答案:

答案 0 :(得分:0)

您可以找到每个连续纬度和经度之间的距离并继续添加。

这里以公里(km)为距离

private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) 
                    * Math.sin(deg2rad(lat2))
                    + Math.cos(deg2rad(lat1))
                    * Math.cos(deg2rad(lat2))
                    * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

希望这会对你有所帮助。