Migrating from the Cordova Device Orientation Plugin

Vishal Mishra
PhoneGap
Published in
2 min readAug 9, 2017

Just like the Cordova Device Motion Plugin , the Cordova Device Orientation Plugin will also see its sunset soon. This plugin provides access to the device’s compass which detects the direction or heading that the device is pointed, typically from the top of the device. The W3C Device Motion and Orientation API now defines a way to access the compass of the device and is supported across iOS, Android and Windows devices. Hence, this Cordova plugin is no longer needed.

Migrating from the plugin to the W3C Device Motion API

The access to the device compass in the Cordova plugin is provided by a global navigator.compass object which provides a method navigator.compass.watchHeading that allows the users to gather the magnetic heading of the compass. The magnetic heading of the compass indicates the heading in degrees from 0–359.99 at a single moment in time. An example to obtain these values is shown below:

function onSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
};

function onError(compassError) {
alert('Compass error: ' + compassError.code);
};

var options = {
frequency: 3000
}; // Update every 3 seconds

var watchID = navigator.compass.watchHeading(onSuccess, onError, options);

However, in the W3C Device Motion and Orientation API, before we gather values from the device’s compass, we need to calibrate the compass by instructing the user to do so:

window.addEventListener("compassneedscalibration",function(event) {
// ask user to wave device in a figure-eight motion
event.preventDefault();
}, true);

Once the compass has been calibrated, the deviceorientation listener can be obtained by:

function processEvent(event) {
// process the event object
},
window.addEventListener("deviceorientation",processEvent, true);

Once the deviceorientation event has been registered, the alpha, beta and gamma values for the device’s orientation can be obtained using the following sample code:

console.log(Math.round(event.alpha));
console.log(Math.round(event.beta));
console.log(Math.round(event.gamma));

The value of magnetic heading which we used to obtain from the watchHeading listener of the Cordova Device Orientation plugin can be gathered by using the value of (360 — event.alpha) .

In the Cordova Device Motion Plugin, the listener for the watchHeading property was removed by using the clearWatch method as shown below:

// watchID created while adding the watchHeading listener
navigator.compass.clearWatch(watchID);

However, according to the W3C Device Motion and Orientation API , the deviceorientation listener can be removed by:

window.removeEventListener("deviceorientation",processEvent);

Your feedback is graciously accepted and appreciated!

--

--