Cordova - Device Orientation
Cordova - Device Orientation (Compass)
Section titled “Cordova - Device Orientation (Compass)”The Device Orientation plugin (specifically, the compass part) provides access to the device’s compass, which indicates the direction or heading the device is pointed, typically relative to geographic North.
Step 1 - Install Device Orientation Plugin
Section titled “Step 1 - Install Device Orientation Plugin”Open your terminal or command prompt, navigate to your Cordova project’s root directory, and run the following command:
your-cordova-project/ cordova plugin add cordova-plugin-device-orientationStep 2 - Add UI Elements (Optional)
Section titled “Step 2 - Add UI Elements (Optional)”Let’s add buttons to get the current heading and to start/stop watching for heading changes. Add this to your index.html:
<body> <button id="getCurrentHeadingBtn">Get Current Heading</button> <button id="watchHeadingBtn">Watch Heading</button> <button id="stopWatchHeadingBtn">Stop Watching</button> <div id="headingInfo">Compass heading will appear here.</div></body>Step 3 - Add Event Listeners
Section titled “Step 3 - Add Event Listeners”In www/js/index.js, inside onDeviceReady, set up listeners for these buttons:
// Inside onDeviceReady in www/js/index.jsdocument.getElementById("getCurrentHeadingBtn").addEventListener("click", getCurrentHeading);document.getElementById("watchHeadingBtn").addEventListener("click", startWatchHeading);document.getElementById("stopWatchHeadingBtn").addEventListener("click", stopWatchHeading);Step 4 - Implement Compass Functions
Section titled “Step 4 - Implement Compass Functions”Define the functions to interact with the compass. The navigator.compass object provides the necessary methods.
const headingDisplay = document.getElementById('headingInfo');let watchCompassID = null;
function getCurrentHeading() { navigator.compass.getCurrentHeading(onCompassSuccess, onCompassError);}
function startWatchHeading() { if (watchCompassID) { // Clear previous watch if any navigator.compass.clearWatch(watchCompassID); } // Watch for changes in heading. Update every 3 seconds for this example. const compassOptions = { frequency: 3000 }; // milliseconds watchCompassID = navigator.compass.watchHeading(onCompassSuccess, onCompassError, compassOptions); headingDisplay.innerHTML = 'Watching compass heading...';}
function stopWatchHeading() { if (watchCompassID) { navigator.compass.clearWatch(watchCompassID); watchCompassID = null; headingDisplay.innerHTML = 'Stopped watching compass.'; } else { headingDisplay.innerHTML = 'Not currently watching compass.'; }}
function onCompassSuccess(heading) { // heading.magneticHeading gives the heading in degrees from 0-359.99 // heading.trueHeading gives the true geographic heading (if available) // heading.headingAccuracy indicates the deviation in degrees between reported and true heading // heading.timestamp is the time at which this heading was determined headingDisplay.innerHTML = `Magnetic Heading: ${heading.magneticHeading.toFixed(2)}°<br/>` + (heading.trueHeading !== undefined ? `True Heading: ${heading.trueHeading.toFixed(2)}°<br/>` : '') + `Accuracy: ${heading.headingAccuracy}°<br/>` + `Timestamp: ${new Date(heading.timestamp).toLocaleTimeString()}`;}
function onCompassError(error) { let errorMsg = 'Compass Error: '; switch (error.code) { case CompassError.COMPASS_INTERNAL_ERR: errorMsg += 'Internal error.'; break; case CompassError.COMPASS_NOT_SUPPORTED: errorMsg += 'Compass not supported on this device.'; break; // Older versions might use numeric codes // case 20: // Example for COMPASS_NOT_SUPPORTED if CompassError is not defined // errorMsg += 'Compass not supported on this device.'; // break; default: errorMsg += `Unknown error (code: ${error.code})`; } headingDisplay.innerHTML = errorMsg; console.error(errorMsg, error);}When “Get Current Heading” is clicked, the current compass heading will be displayed. For instance: “Magnetic Heading: 123.45°”.
Clicking “Watch Heading” will continuously update the heading every 3 seconds (as per frequency: 3000). “Stop Watching” will clear this interval update.
If the device does not have a compass or an error occurs, the onCompassError function will be called. For example, if the device lacks a magnetic sensor, it might display: “Compass Error: Compass not supported on this device.”.
Important Notes
Section titled “Important Notes”- Device Support: Not all devices have a hardware compass. Always check for support or handle errors gracefully.
- Accuracy: Compass readings can be affected by magnetic interference. Some platforms might provide accuracy information.
- Permissions: On some platforms, using the compass might require location permissions, as it can be used to infer location.
- True Heading vs. Magnetic Heading:
magneticHeadingis the raw reading.trueHeadingis corrected for magnetic declination (difference between magnetic north and true north), but may not always be available.