java Android Location getBearing() 总是返回 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31388063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:31:56  来源:igfitidea点击:

Android Location getBearing() always returns 0

javaandroidlocationlocationmanagerbearing

提问by user3171597

I've been trying to implement a feature for my Android app that gets the speed and direction of travel of the device, no matter where the device is pointed at. For example: If my Android device is pointed in the North direction and if I'm moving backwards in the South direction, it would return that I'm moving Southbound.

我一直在尝试为我的 Android 应用程序实现一项功能,该功能可以获取设备的速度和行进方向,无论设备指向何处。例如:如果我的 Android 设备指向北方,如果我向南向后移动,它会返回我正在向南移动。

I've been looking around and I have came up with a possibility of using the Location's getBearing() method (Still, I do not know if that will solve my whole problem). When I invoke getBearing(), it always returns 0.0 for some reason. I have no idea why. Here is my code:

我一直在环顾四周,我想出了使用 Location 的 getBearing() 方法的可能性(不过,我不知道这是否能解决我的整个问题)。当我调用 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);
}

This is where I am getting the bearing.

这是我得到轴承的地方。

@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;

}

Thanks so much!

非常感谢!

采纳答案by Matt Newbill

getBearing()will return 0 if you are obtaining your data using LocationManager.NETWORK_PROVIDERbecause the signal/accuracy is too weak. Try setting the GPS provider to GPS and be sure to test it outside (GPS does not work indoors or in the middle of very tall buildings due to satellites not having direct communication)

getBearing()如果LocationManager.NETWORK_PROVIDER由于信号/精度太弱而使用获取数据,则将返回 0 。尝试将 GPS 提供商设置为 GPS 并确保在室外进行测试(由于卫星没有直接通信,GPS 在室内或非常高的建筑物中间不起作用)

To ensure the provider you have chosen supports getBearing() you can use the method from LocationProvidercalled supportsBearing ()which returns true if the provider you have chosen supports the getBearing()call.

为确保您选择的提供者支持 getBearing(),您可以使用来自LocationProvider调用的方法,supportsBearing ()如果您选择的提供者支持该getBearing()调用,则该方法返回 true 。

Lastly ensure that you have the ACCESS_COARSE_LOCATIONor ACCESS_FINE_LOCATIONpermissions in your AndroidManifest.xml

最后确保您在 AndroidManifest.xml 中拥有ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION权限

Code as per my suggestions would be something like this:

根据我的建议,代码将是这样的:

LocationManager mlocManager =

(LocationManager)getSystemService(Context.LOCATION_SERVICE);

LocationListener mlocListener = new MyLocationListener();


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

Resources: http://developer.android.com/reference/android/location/LocationManager.htmlhttp://developer.android.com/reference/android/location/LocationProvider.htmlhttp://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/

资源: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/

UPDATE: The answer was that the two points that were being used to calculate in getBearing() were too close and therefore giving an inaccurate result. To correct this, manually grab two GPS points and use the bearingTo() to see a more accurate result.

更新:答案是在 getBearing() 中用于计算的两个点太接近了,因此给出了不准确的结果。要纠正此问题,请手动抓取两个 GPS 点并使用bearingTo() 来查看更准确的结果。