”;
Compass is used to show direction relative to geographic north cardinal point.
Step 1 – Install Device Orientation plugin
Open the command prompt window and run the following.
C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugindevice-orientation
Step 2 – Add Buttons
This plugin is similar to the acceleration plugin. Let us now create two buttons in index.html.
<button id = "getOrientation">GET ORIENTATION</button> <button id = "watchOrientation">WATCH ORIENTATION</button>
Step 3 – Add Event Listeners
Now, we will add event listeners inside the onDeviceReady function in index.js.
document.getElementById("getOrientation").addEventListener("click", getOrientation); document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
Step 4 – Creating Functions
We will create two functions; the first function will generate the current acceleration and the other will check on the orientation changes. You can see that we are using the frequency option again to keep a watch on changes that occur every three seconds.
function getOrientation() { navigator.compass.getCurrentHeading(compassSuccess, compassError); function compassSuccess(heading) { alert(''Heading: '' + heading.magneticHeading); }; function compassError(error) { alert(''CompassError: '' + error.code); }; } function watchOrientation(){ var compassOptions = { frequency: 3000 } var watchID = navigator.compass.watchHeading(compassSuccess, compassError, compassOptions); function compassSuccess(heading) { alert(''Heading: '' + heading.magneticHeading); setTimeout(function() { navigator.compass.clearWatch(watchID); }, 10000); }; function compassError(error) { alert(''CompassError: '' + error.code); }; }
Since the compass plugin is almost the same as the acceleration plugin, we will show you an error code this time. Some devices do not have the magnetic sensor that is needed for the compass to work. If your device doesn”t have it, the following error will be displayed.
”;