May 21, 2021 Cordova
The compass is used to show the direction relative to the geographic north base point.
Open the command prompt window and run the following command.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation
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>
Now we'.js event listener to the onDeviceReady function in index data.
document.getElementById("getOrientation").addEventListener("click", getOrientation); document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
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.