The compass API uses a single axis to calculate the heading, depending on the orientation of the device. The device may be flat with its screen facing up, or it may be in an upright portrait position.
The Compass
class does not provide the means to determine which orientation it is using; rather, you use an Accelerometer
to tell you.
The viewmodel’s Start
method also includes the initialization of an Accelerometer
(see Listing 16.6).
public void Start()
{
...
accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += HandleAccelerometerCurrentValueChanged;
accelerometer.Start();
}
The orientation of the compass is represented using a custom enum called CompassOrientation
. It has two values: Flat and Portrait. Listing 16.7 shows how the Accelerometer
’s CurrentValueChanged
event handler calculates the orientation of the device using the Y and Z dimensional components of the reading vector.
void HandleAccelerometerCurrentValueChanged(
object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
Vector3 accelerationVector = e.SensorReading.Acceleration;
bool usingNegativeZAxis = false;
/* Determine the orientation of the device. */
if (Math.Abs(accelerationVector.Z) < Math.Cos(Math.PI / 4)
&& accelerationVector.Y < Math.Sin(7 * Math.PI / 4))
{
usingNegativeZAxis = true;
}
CompassOrientation = usingNegativeZAxis
? CompassOrientation.Portrait
: CompassOrientation.Flat;
}
18.219.111.195