Расположение Android getBearing() всегда возвращает 0

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

Я искал и нашел возможность использовать метод getBearing() для Location (тем не менее, я не знаю, решит ли это всю мою проблему). Когда я вызываю getBearing(), он всегда возвращает 0.0 по какой-то причине. Понятия не имею почему. Вот мой код:

LocationManager lm;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gcm);
    setUpUI(findViewById(R.id.LinearLayout1));
    isRegged = false;

    // GCM startup
    gcm = GoogleCloudMessaging.getInstance(this);
    context = getApplicationContext();

    gps = new GPSTracker(context);
    // gps.startListening(context);
    // gps.setGpsCall(this);

    /*
     * Variables to indicate location and device ID
     */
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    if (gps.getIsGPSTrackingEnabled())
    {
        longitude = Double.valueOf(gps.getLongitude()).toString();
        latitude = Double.valueOf(gps.getLatitude()).toString();
    }

    deviceID = telephonyManager.getDeviceId();

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, (float) 0.0,
            this);
}

Это где я получаю подшипник.

@Override
public void onLocationChanged(Location currentLocation)
{
    float speed = 0;
    float speed_mph = 0;

    if (previousLocation != null)
    {
        float distance = currentLocation.distanceTo(previousLocation);

        // time taken (in seconds)
        float timeTaken = ((currentLocation.getTime() - previousLocation
                .getTime()) / 1000);

        // calculate speed
        if (timeTaken > 0)
        {
            speed = getAverageSpeed(distance, timeTaken);
            speed_mph = (float) (getAverageSpeed(distance, timeTaken) / 1.6);
        }

        if (speed >= 0)
        {
            info_text.setVisibility(View.VISIBLE);
            info_text_mph.setVisibility(View.VISIBLE);

            DecimalFormat df = new DecimalFormat("#.#");
            info_text.setText("Speed: " + df.format(speed) + " " + "km/h");
            info_text_mph.setText("  Speed: " + df.format(speed_mph) + " "
                    + "mph");

            if (speed >= 10 && lm.getProvider(LocationManager.GPS_PROVIDER).supportsBearing())
            {
                float degree = currentLocation.getBearing();

                direction_text.setVisibility(View.VISIBLE);

                Log.i(TAG, String.valueOf(degree));

                if (degree == 0 && degree < 45 || degree >= 315
                        && degree == 360)
                {
                    direction_text.setText("You are: Northbound");
                }

                if (degree >= 45 && degree < 90)
                {
                    direction_text.setText("You are: NorthEastbound");
                }

                if (degree >= 90 && degree < 135)
                {
                    direction_text.setText("You are: Eastbound");
                }

                if (degree >= 135 && degree < 180)
                {
                    direction_text.setText("You are: SouthEastbound");
                }

                if (degree >= 180 && degree < 225)
                {
                    direction_text.setText("You are: SouthWestbound");
                }

                if (degree >= 225 && degree < 270)
                {
                    direction_text.setText("You are: Westbound");
                }

                if (degree >= 270 && degree < 315)
                {
                    direction_text.setText("You are: NorthWestbound");
                }

            }

        }
    }
    previousLocation = currentLocation;

}

Спасибо!

1 ответ

Решение

getBearing() вернет 0, если вы получаете ваши данные, используя LocationManager.NETWORK_PROVIDER потому что сигнал / точность слишком слабая. Попробуйте настроить GPS-провайдер на GPS и не забудьте проверить его снаружи (GPS не работает в помещении или в центре очень высоких зданий из-за того, что спутники не имеют прямой связи)

Чтобы убедиться, что выбранный вами провайдер поддерживает getBearing(), вы можете использовать метод из LocationProvider называется supportsBearing () возвращает true, если выбранный вами провайдер поддерживает getBearing() вызов.

Наконец, убедитесь, что у вас есть ACCESS_COARSE_LOCATION или же ACCESS_FINE_LOCATION разрешения в вашем AndroidManifest.xml

Код в соответствии с моими предложениями будет что-то вроде этого:

LocationManager mlocManager =

(LocationManager)getSystemService(Context.LOCATION_SERVICE);

LocationListener mlocListener = new MyLocationListener();


mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

Ресурсы: http://developer.android.com/reference/android/location/LocationManager.html http://developer.android.com/reference/android/location/LocationProvider.html http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/ с использованием GPS-к-получить ток-местоположение-2 /

ОБНОВЛЕНИЕ: Ответ состоял в том, что две точки, которые использовались для вычисления в getBearing(), были слишком близки и, следовательно, давали неточный результат. Чтобы исправить это, вручную возьмите две точки GPS и используйте подшипник To (), чтобы увидеть более точный результат.

Другие вопросы по тегам