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<=azimuth<360 但是当我旋转我的设备时,我只得到从 -3 到 3 的值。有人可以告诉我问题可能是什么吗?

4

3 回答 3

12

这些值以弧度为单位,您必须转换为弧度

int azimut = (int) Math.round(Math.toDegrees(orientation[0]));
于 2013-03-01T11:42:23.217 回答
7

这是真的,它是在弧度。谢谢霍恩。我添加了一些逻辑来获得从 0 到 360 的度数,因为如果我只将它转换为度数,我得到的值是从 -180 到 180。

float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians)+360)%360;
于 2013-03-01T12:54:10.883 回答
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));

}
于 2015-01-14T08:19:36.647 回答