The Cordova Plugin Device Orientation enables access to the device’s compass and gyroscope features for mobile applications built with Apache Cordova.
Installation
- Make sure you have the Cordova CLI installed globally on your machine.
- Navigate to your project directory using the command prompt or terminal.
- Run the following command:
cordova plugin add cordova-plugin-device-orientation
Usage
Getting the Current Compass Heading
In order to retrieve the current compass heading, you need to use the following function:
navigator.compass.getCurrentHeading(onSuccess, onError);
The onSuccess
parameter is a callback function that will be invoked with the compass data. An example of an onSuccess
function could be:
function onSuccess(heading) {
console.log('Compass heading: ' + heading.magneticHeading);
}
Watching the Compass Heading
If you require continuously updated compass heading values, you can use the following function:
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
The onSuccess
parameter of watchHeading
is similar to getCurrentHeading
. The difference is that onSuccess
will be invoked whenever the compass heading changes. To stop watching the compass heading, you can use:
navigator.compass.clearWatch(watchID);
Getting the Current Device Orientation
In order to retrieve the device’s current orientation, you can use the following function:
navigator.compass.getCurrentOrientation(onSuccess, onError);
Watching the Device Orientation
If you need continuous updates on the device’s orientation, you can use:
navigator.compass.watchOrientation(onSuccess, onError);
The onSuccess
parameter of watchOrientation
is a callback function that will be invoked when the device’s orientation changes. To stop watching the device’s orientation, you can use:
navigator.compass.clearWatch(watchID);
Supported Platforms
- iOS
- Android
- Windows
Additional Resources
For additional information, you can refer to the official Cordova Plugin Device Orientation documentation.