Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cordova device orientation


May 21, 2021 Cordova


Table of contents


The compass is used to show the direction relative to the geographic north base point.

Step 1 - Install the device orientation plug-in

Open the command prompt window and run the following command.

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation

Step 2 - Add a button

If you follow our last tutorial, you may notice that this plug-in is similar to the Acceleration plug-in. /b10> In this tutorial, we'll follow the same concept. /b11> Let's .html buttons in the index file.

<button id = "getOrientation">GET ORIENTATION</button>
<button id = "watchOrientation">WATCH ORIENTATION</button>

Step 3 - Add an event listener

Now we'.js event listener to the onDeviceReady function in index data.

document.getElementById("getOrientation").addEventListener("click", getOrientation);
document.getElementById("watchOrientation").addEventListener("click", watchOrientation);

Step 4 - Create a function

We'll create two functions, one to get the current acceleration and the other to see the direction change. /b10> You can see that we're using the Frequency option because we want to see the changes 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 plug-in is almost identical to the acceleration plug-in, we will display the error code at this time. /b10> Some devices do not have the magnetic sensors required for the magnetic disc to work. /b11> If your device doesn't have it, you'll get the following error.

Cordova device orientation