Android指南针方位角

9

我正在尝试使用以下方法以度数(即0-360)获取指南针方位:

float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = event.values;
    if (mGravity != null && mGeomagnetic != null) {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
                mGeomagnetic);
        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimut = orientation[0];
            bearing.setText("Bearing: "+ azimut);
        }
    }
}

方位角值(即orientation[0])应该是0 <= 方位角 < 360,但我旋转设备时只得到-3到3的值。请问有人能告诉我问题可能是什么吗?
3个回答

12

这些数值是弧度制,你需要将其转换为角度制。

int azimut = (int) Math.round(Math.toDegrees(orientation[0]));

orientation[0] 似乎只提供了自上次读取以来的差异。我已将我的值转换为度数,但值仍然非常小。有没有一种方法可以在单次读取中获取设备的实际方位(0-360度)? - Andrew Kelly
1
这不是差异,而是相对于磁北极的实际方位角。如果你的读数总是一个小值,那么你的代码可能有问题。 - Hoan Nguyen
1
原来我的指南针没有校准,在执行八字形运动后(另一个我下载的指南针应用程序提示我这样做,但它也显示不正确的值),我现在收到的值是我所期望的。 - Andrew Kelly

8

确实是以弧度为单位。谢谢 Hoan。我添加了一些逻辑,将该方位角从0到360度转换,因为如果仅将其转换为角度,则会得到从-180到180的值。

float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians)+360)%360;

1
// This answer applies to Google Maps api v2.
// It is possible by registering your application with Sensor Listener for Orientation and get the
// angle relative to true north inside onSensorChanged and update camera accordingly.
// Angle can be used for bearing. Following code can be used:

// Instead of using Sensor.TYPE_ORIENTATION try using getOrinetation api. Sensor.TYPE_ORIENTATION
// has been deprecated.

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    if (sensorManager != null)
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
}

public void onSensorChanged(SensorEvent event) {

    float compassBearingRelativeToTrueNorth = Math.round(event.values[0]);

    Log.d(TAG, "Degree ---------- " + degree);

    updateCamera(compassBearingRelativeToTrueNorth);

}

private void updateCamera(float bearing) {
    CameraPosition oldPos = googleMap.getCameraPosition();

    CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing)
            .build();

    googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接