java - 计算行驶的距离(不是之间的距离)

标签 java android kotlin distance

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

关于如何获取汽车行驶的距离有什么建议吗?

我尝试过使用 Google 的位置 API:distanceTo 或 distanceBetween 根本不是一个选项。它可以给出与实际结果显着不同的结果。在真实的汽车中,它可以穿过很短的地方,并在 800 米内到达目标,而 Google 可以给出位置之间 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()
    }
}

最佳答案

我已经实现了一个基于 GPS 读数的里程表,并且通过一秒钟的读数,我已经能够获得远低于 1% 精度误差的里程表讲座。在远达 50-70 公里的距离上,我无法检测到与道路标记超过 50 m 的差异(我什至能够检测到标记何时移动)。所使用的程序涉及整合速度读数(速度由 GPS 给出,如下所示):一个 vector ,因此不需要计算它的模数)和设备给出的时间戳的精确读数。切勿使用位置读数...因为这些读数足以使您的里程表偏离读数超过 20%。但是使用速度并对其进行积分可以为您提供良好的低音带通滤波。

使用的 GPS 是具有 NMEA.0183 输出的标准 OEM GPS。速度读数的分辨率为 0.1 值,因此我没想到精度会低于 1%,目前的 GPS 设备给出的速度读数分辨率低于 0.001。

关于java - 计算行驶的距离(不是之间的距离),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54628576/

相关文章:

java - 如何在没有JDK的情况下运行jcmd?

java - 使用集合查询 @Entity 中的 @ElementCollection

android - Cordova 错误在 cmd 命令 : cordova Build android

java - 从 HttpPost Android 中提取 URL

android - ListAdapter 未更新 RecyclerView 中的项目

reflection - 如何在Kotlin中声明一组可反射的函数?

java - BufferedInputStream 没有标记

android - 为什么我的 android 应用程序在 playstore 中显示应用内购买优惠

intellij-idea - 如何使用 IntelliJ 调试器在 Kotlin require 中设置断点?

java - 在java中存储来自传感器的数据的最快方法