当前位置: 首页 > 知识库问答 >
问题:

计算行驶距离(不是距离)

谭畅
2023-03-14

我需要计算汽车行驶的距离!不是距离,不是距离到否。如果我们通过谷歌提供的API计算,距离可以完全不同。谷歌可以提供从一个点到另一个点的1公里距离,但汽车可以按照骑手想要的方式行驶800米。使用加速计没有帮助。它适用于步行,但绝不适用于更快的速度。

我尝试过使用Google的位置API:距离到或距离之间根本不是一个选项。它可以给出与IN REAL截然不同的结果。在真实的汽车中,可以通过非常短的地方并在800米内到达目标,而谷歌可以在位置之间提供1公里的距离。

下面是我的应用程序代码。速度惊人地正确。

class HomeScreen : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, SensorEventListener {
    override fun onSensorChanged(event: SensorEvent?) {
        val sensor = event?.sensor
        val values = event?.values
        var value = -1

        if (values != null && values.size ?: 0 > 0) {
            value = values[0].toInt()
        }


        if (sensor != null &&
            sensor.type == Sensor.TYPE_STEP_DETECTOR
        ) {
            val finalSteps = getDistanceRun(steps)
            val finalStepsTruncated = String.format("%.2f", finalSteps)
            distanceTV.text = "$finalStepsTruncated"
            steps++
        }
    }

    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

    }

    override fun onConnectionFailed(p0: ConnectionResult) {
        val failed = p0
    }

    @SuppressLint("MissingPermission")
    override fun onConnected(p0: Bundle?) {
        if (locationPermissionsGranted(this)) {
            fusedLocationClient?.requestLocationUpdates(locationRequest, object : LocationCallback() {
                override fun onLocationResult(p0: LocationResult?) {
                    val location = p0
                    val metersPerSecond: Float = location?.lastLocation?.speed ?: 0f
                    val speed = metersPerSecond * 3600 / 1000
                    speedTV.text = "${Math.round(speed)} KM/H"
                }
            }, null)

        } else {
            requestPermission(
                this, 0,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
            )
        }
    }

    override fun onConnectionSuspended(p0: Int) {
        val suspended = p0
    }

    private var fusedLocationClient: FusedLocationProviderClient? = null
    private var mGoogleApiClient: GoogleApiClient? = null
    private lateinit var locationRequest: LocationRequest
    private var steps: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home_screen)
        locationRequest = LocationRequest()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
        locationRequest.interval = 1000
        locationRequest.fastestInterval = 500

        if (PermissionManager.locationPermissionsGranted(this)) {
            mGoogleApiClient = GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build()

            mGoogleApiClient?.connect()
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            createLocationRequest()
        } else {
            requestPermission(
                this, 0,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
            )
        }

        val sManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val stepSensor = sManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
        sManager.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (PermissionManager.locationPermissionsGranted(this)) {
            mGoogleApiClient = GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build()
            mGoogleApiClient?.connect()
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
            createLocationRequest()
        }
    }

    protected fun createLocationRequest() {
        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)

        val client = LocationServices.getSettingsClient(this)
        val task = client.checkLocationSettings(builder.build())

        task.addOnSuccessListener(this) {

            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
        }

        task.addOnFailureListener(this) { e ->

            if (e is ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    e.startResolutionForResult(
                        this@HomeScreen,
                        0
                    )
                } catch (sendEx: IntentSender.SendIntentException) {
                    // Ignore the error.
                }

            }
        }
    }

    fun getDistanceRun(steps: Long): Float {
        return (steps * 78).toFloat() / 100000.toFloat()
    }
}

共有2个答案

傅志文
2023-03-14

您好,我不知道这是否有帮助,但我曾经编写过一个类,在该类中,我通过将参数输入到相应的方法来手动计算:

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.util.List;

/**
 * Created by Ibkunle Adeoluwa on 1/8/2019.
 */


public class LocationManager {

    private FusedLocationProviderClient fusedLocationProviderClient;
    private LocationCallback locationCallback;
    private LocationRequest locationRequest;



    //TODO Import these Libraries in gradle
    /*
    implementation 'com.google.android.gms:play-services-location:11.8.0'
    implementation 'com.karumi:dexter:5.0.0'
    */

    private Activity myActivity;

    public LocationManager(Activity myActivity) {
        this.myActivity = myActivity;
    }


    public void requestLocationPermissions() {
        //Request required permissions using Dexter Library ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION
        Dexter.withActivity(myActivity)
                .withPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            buildLocationRequest();
                            buildLocationCallback();
                            if (ActivityCompat.checkSelfPermission(myActivity, Manifest.permission.ACCESS_FINE_LOCATION)
                                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(myActivity, Manifest.permission.ACCESS_COARSE_LOCATION)
                                    != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(myActivity);
                            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        Toast.makeText(myActivity, "Location Permission Denied", Toast.LENGTH_SHORT).show();

                    }
                }).check();
    }


    private void buildLocationRequest() {
        //Get Location
        locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setSmallestDisplacement(10.0f);
    }

    private Location buildLocationCallback() {
        //Process location response
        final Location location = new Location();

        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                //Log
                Log.d("Location", locationResult.getLastLocation().getLatitude()
                        + "/" + locationResult.getLastLocation().getLongitude());

                location.setLatitude(locationResult.getLastLocation().getLatitude());
                location.setLongitude(locationResult.getLastLocation().getLongitude());


            }
        };
        return location;
    }

    //TODO How to Use

    /***
     * Sample Request
     *
     System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') + " Miles\n");
     System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'K') + " Kilometers\n");
     System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'N') + " Nautical Miles\n");

     System.out.println(distance(10.46786, -98.53506,32.9697, -96.80322,  'M') + " Initial Miles\n");
     System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, 'M') + " Covered Miles\n");

     System.out.println(coveredDistance(distance(10.46786, -98.53506,32.9697, -96.80322), distance(32.9697, -96.80322, 29.46786, -98.53506))+ " Left Distance\n");

     System.out.println(percentageCoveredDistance(262.6777938054349,1558.5453389875424)+ " Covered Distance Percentage \n");
     *
     *
     ***/


    /**
     * Expected Output
     *
     262.6777938054349 Miles
     422.73893139401383 Kilometers
     228.10939614063963 Nautical Miles

     1558.5453389875424 Initial Miles
     262.6777938054349 Covered Miles

     1295.8675451821075 Left Distance
     17% Covered Distance Percentage
     *
     *
     **/


    /**
     *
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @param unit
     * @return
     */
    private static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
        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;
        if (unit == 'K') {
            dist = dist * 1.609344;
        } else if (unit == 'N') {
            dist = dist * 0.8684;
        }
        return (dist);
    }

    /**
     *
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @return
     */
    private static 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);
    }

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts decimal degrees to radians             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

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

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts radians to decimal degrees             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

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

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts subtracts initial from current distance:*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

    /**
     *
     * @param initialDistance
     * @param currentDistance
     * @return
     */
    private static double coveredDistance(double initialDistance, double currentDistance) {
        return (initialDistance - currentDistance);
    }

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::This function converts the covered distance to percentage of the total :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

    /**
     *
     * @param coveredDistance
     * @param totalDistance
     * @return
     */
    private static String percentageCoveredDistance(double coveredDistance, double totalDistance) {
        double percent = (100 * coveredDistance) / totalDistance;
        return String.format("%.0f%%", percent);
    }


}
沈巴英
2023-03-14

我已经实现了一个基于gps读数的里程表,通过一秒钟的读数,我可以得到里程表的讲课精度远低于1%的误差。距离远达50-70km时,我无法检测到距离道路标记超过50m的差异(我甚至能够检测到标记何时移动)。使用的程序包括整合速度读数(速度由gps作为矢量给出,因此无需计算其模数)和设备给出的时间戳的精确读数。切勿使用位置读数。。。因为这些都很糟糕,足以让你的里程表在读数中偏离20%以上。但是使用速度和积分这些可以得到很好的低音带通滤波。

使用的GPS是具有NMEA.0183输出的标准OEM gps。速度读数的分辨率为0.1值,因此我不期望精度低于1%,目前的gps设备提供的速度读数分辨率低于0.001。

 类似资料:
  • 我目前正在开发一个专注于健身的应用程序。我的基本想法是允许人们跟踪他们的速度、距离和时间。到目前为止,我已经通过使用位置管理器getSpeed()设法获得了速度。我想知道如何获得旅行的距离?我寻找了一些示例,但对我来说有点困惑,因为我刚刚开始使用android。我将感谢任何帮助或建议,谢谢

  • 问题内容: 如何在Swift中使用CoreLocation计算行进的总距离 到目前为止,我还无法找到有关如何在iOS 8的Swift中执行此操作的任何资源。 自开始跟踪位置以来,您将如何计算移动的总距离? 根据到目前为止的读物,我需要保存一个点的位置,然后计算当前点与最后一个点之间的距离,然后将该距离添加到totalDistance变量中 Objective-C对我来说是非常陌生的,所以我还无法计

  • 我正在尝试写我的第一次postgis查询 我的桌子如下所示 这是一辆id为1的车辆的gps数据。我需要计算车辆行驶的总距离,比方说2017-05-20年,以米为单位。可以有其他具有不同ID的视图。 参考(如)。https://gis.stackexchange.com/Questions/268776/Finding-Total-Distance of-Path-Along-Post-PointG

  • 我有一个多边形类型的几何体,我正在计算一个点的最小距离可能在多边形几何体内部(由360个点组成,作为闭合几何体)或多边形几何体外部。使用postgis的ST_distance方法,当点在几何体外部时,我得到精确的距离,但如果点在几何体内部,则得到0作为距离,我想要与多边形几何体最近点的点之间的最小距离,无论该点位于几何体内部还是外部。

  • 问题内容: 我在用 python 2.7.12 Django 1.10.6 PostgreSQL 9.5.6 postGIS 2.2.2 第一个问题 我需要使用GeoDjango计算两点之间的距离。当我检查了 文档它说, GeoQuerySet.distance() 已被弃用,而使用 距离() 从 django.contrib.gis.db.models.functions 。 以下代码可以正常工

  • 我试图使用Scala类计算两点之间的距离。但它给出了一个错误说 类型不匹配;发现:其他。需要类型(具有基础类型点):?{def x:?}请注意,隐式转换不适用,因为它们是不明确的:在[A](x:A)类型的对象Predef中确保[A]的方法any2Ensuring和在[A](x:A)“ArroAssoc[A]类型的对象Predef中的方法Ani2ArrowasSoc都是可能的其他转换函数。输入到?{