Compass Orientation

,

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).

LISTING 16.6. CompassViewModel.Start Method (excerpt 2)


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.

LISTING 16.7. HandleAccelerometerCurrentValueChanged Method


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


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.111.195