Retrieving compass data in complex apps
Collapse the table of content
Expand the table of content

Retrieving compass data in complex apps (Windows Runtime apps)

An app can track changes in device heading by registering to receive event notifications from the Compass class that represents the compass of the device. Depending on the implementation of the sensors, an app may also be able to choose between headings relative to true north or magnetic north.

The following code examples demonstrate how to retrieve the default compass for a device and then register a ReadingChanged event handler to receive notifications when the sensor issues a new reading.

compass = Windows.Devices.Sensors.Compass.getDefault();

function enableReadingChangedScenario() {
    if (compass) {
        // Set the reportInterval to enable the sensor events
        compass.reportInterval = reportInterval;

        document.addEventListener("msvisibilitychange", msVisibilityChangeHandler, false);
        compass.addEventListener("readingchanged", onDataChanged);
        document.getElementById("scenario1Open").disabled = true;
        document.getElementById("scenario1Revoke").disabled = false;
    } else {
        WinJS.log && WinJS.log("No compass found", "sample", "error");

The ReadingChanged event handler then receives the new heading relative to magnetic north, and the heading relative to true north if it exists, as shown in the following code example.

function onDataChanged(e) {
    var reading = e.reading;

    document.getElementById("eventOutputMagneticNorth").innerHTML = reading.headingMagneticNorth.toFixed(2);
    if (reading.headingTrueNorth) {
        document.getElementById("eventOutputTrueNorth").innerHTML = reading.headingTrueNorth.toFixed(2);



© 2017 Microsoft