Метод distanceTo не дает результата, всегда возвращает 0.0km - PullRequest
0 голосов
/ 20 октября 2019

Я пытаюсь получить расстояние между двумя точками, но я всегда получаю результат 0,0 км.

Я пробовал 2 версии, но обе они дают мне результат 0,0км .

  1. Версия с LatLng

  2. Версия с местоположением

Эта версияс местоположением

private fun onLocationchanged(location:Location):Float {

        if(mStartLocation == null)
        {
            mStartLocation  = mCurrentLocation
            mEndLocation = mCurrentLocation
        }
        else {
            mEndLocation = mCurrentLocation
        }
        mCurrentLocation = location;
        val distance = mStartLocation.distanceTo(mEndLocation)
        tvDistanzKm.text = distance.toString()
        return distance
        //Testing...No Difference
        val currentLocation = mStartLocation.latitude
        tvStart.text = currentLocation.toString()
        val endLocation = mEndLocation.latitude
        tvEnd.text = endLocation.toString()
    }

Эта версия с LatLang

fun getLaufDistanz():Float {

if(mLatLngStart == null) {
    mLatLngStart = mLatLngCurrent
    mLatLngEnde = mLatLngCurrent
}else{
    mLatLngEnde = mLatLngCurrent
}
val laufStartPunkt = Location("")
laufStartPunkt.latitude = mLatLngCurrent.latitude
laufStartPunkt.longitude = mLatLngCurrent.longitude

val laufEndPunkt = Location("")
laufEndPunkt.latitude = mLatLngCurrent.latitude
laufEndPunkt.longitude = mLatLngCurrent.longitude

val laufDistanzInMeter = laufStartPunkt.distanceTo(laufEndPunkt)
tvDistanzKm.text = laufDistanzInMeter.toString()
return laufDistanzInMeter

}

Это мой обратный вызов

      //Result is always 0.0km
                    val distance = mStartLocation.distanceTo(mEndLocation)
                    tvDistanzKm.text = distance.toString()

                    //Testing...No Difference
                  //  mStartLocation == mEndLocation ???????
                    val currentLocation = mStartLocation.latitude
                    tvStart.text = currentLocation.toString()
                    val endLocation = mEndLocation.latitude
                    tvEnd.text = endLocation.toString()

                    //Testing the latitude/longitude in TextView
                    tvLatitude.text = location.latitude.toString()
                    tvLongitude.text = location.longitude.toString()

                    if (location != null) {
                          if (location.hasSpeed()) {
                            val getkmh = (location.speed * 3.6)
                            tvTempo.text = getkmh.toString()
                            tvSpeed.text = location.speed.toString()
                        } else {
                            tvTempo.text = "0.00"
                            tvSpeed.text = "0.00"
                        }
                        if (location.hasAccuracy()) {
                            tvAccuracy.text = location.accuracy.toString()
                        } else {
                            tvAccuracy.text = "schlechte Ortung"
                        }
                        if (location.hasAltitude()) {
                            tvAltitude.text = location.altitude.toString()
                        } else {
                            tvAltitude.text = "Nix Höhe"
                            Toast.makeText(
                                applicationContext,
                                "keine Höhe erkannt",
                                Toast.LENGTH_SHORT
                            )
                                .show()
                        }
                         startLocationUpdates()
                        updatePolyline()
                        buttons()
                        onLocationchanged(location)
                        getLaufDistanz()
                    }

я не знаю гдепроблема в том, пожалуйста, помогите мне. спасибо.

я пробовал это по-разному, но всегда безрезультатно.

я не нашел решения онлайн, также не на stackoverflow.

яновичок в Kotlin.

спасибо

Ответы [ 2 ]

1 голос
/ 20 октября 2019

Вы устанавливаете mStartLocation и mEndLocation на один и тот же объект, поэтому расстояние должно быть 0,0 между ними. Смотрите свою логику здесь:

    if(mStartLocation == null)
    {
        mStartLocation  = mCurrentLocation
        mEndLocation = mCurrentLocation
    }
    else {
        mEndLocation = mCurrentLocation
    }
    //after above lines, both mEndLocation and mStartLocation point at the same object
    mCurrentLocation = location; // this will have no effect on next line
    val distance = mStartLocation.distanceTo(mEndLocation) //doesn't use "location"

В вашем коде выше самое последнее местоположение, переданное в эту функцию, даже не используется как часть формулы. Я думаю, это должно быть так просто:

var previousLocation: Location? = null
var totalDistance = 0f

private fun onLocationchanged(location:Location): Float {
    val distance = previousLocation?.distanceTo(location) ?: 0f
    previousLocation = location
    totalDistance += distance
    tvDistanzKm.text = totalDistance.toString()
    return totalDistance
}
0 голосов
/ 21 октября 2019

Расположение в км или м -

private fun distanceLoc(location1: Location, location2: Location): String {
        val theta = location1.longitude - location2.longitude
        var dist = (sin(degToRad(location1.latitude))
                * sin(degToRad(location2.latitude))
                * cos(degToRad(location1.latitude))
                * cos(degToRad(location2.latitude))
                * cos(degToRad(theta)))
        dist = acos(dist)
        dist = radToDeg(dist)
        dist *= 60.0 * 1.1515
        var distStr = "$dist Km."
        if (dist < 0) {
            dist *= 1000
            distStr = "$dist Meter"
        }
        return distStr
    }

    private fun radToDeg(rad: Double): Double {
        return rad * 180 / Math.PI
    }

    private fun degToRad(deg: Double): Double {
        return deg * Math.PI / 180.0
    }
...