ARTICLE

Compass in PhoneGap

Posted by Richa Garg Articles | Windows Phone August 01, 2012
In this article I will explain how to use compass in PhoneGap/Apache Cordova.
Reader Level:

Introduction

A compass is used to obtain the direction that the device is pointing. There are various methods and arguments that we use for a compass; these are:

1 ) compass.getCurrentHeading

This method is used to get the current compass heading, it is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99. The supported platforms are Android, iPhone, Window Phone 7 (Mango) and if available in hardware, Bada 1.2 & 2.x and webOS. The syntax is:

navigator.compass.getCurrentHeading( compassSuccess, compassError, compassOption);

compassSuccess : It is used to provide the onSuccess callback function that provides the compass heading information via a compassHeading object. It takes one parameter, heading that provides the heading information; for example:

function onSuccess(heading)
{

    alert('Heading: ' + heading.magneticHeading);
};


compassError : It is used to give the onError callback function for compass functions. Example:

function(CompassError)

{

   // Handle the error

}

compassOption : It is an optional parameter that is used to customize the retrieval of the compass. It takes two options, frequency that retrieves the compass heading in miliseconds and the filter that will change the degrees required to initiate a watchHeading success callback.

Example of this method is:
 

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

    <title>Cordova WP7</title>

    <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title"

        charset="utf-8" />

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>

    <script type="text/javascript">

        // Wait for Cordova to load      

        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready

        function onDeviceReady() {

            navigator.compass.getCurrentHeading(onSuccess, onError);

        }

        // onSuccess: Get the current heading     

        function onSuccess(heading) {

            alert('Heading: ' + heading.magneticHeading);

        }

        // onError: Failed to get the heading      

        function onError(compassError) {

            alert('Compass Error: ' + compassError.code);

        }

    </script>

</head>

<body>

    <h1>

        Example</h1>

    <p>

        getCurrentHeading</p>

</body>

</html>

2 ) compass.watchHeading

The compass.watchHeading gets the device's current heading at a regular interval. Each time the heading is retrieved the heading Success callback function is executed. We can specify the interval in miliseconds via the frequency parameter in the compassOptions object. It returns the watch Id that can be used with compass.clearWatch to stop watching the compass. The supported platform are Android, iPhone, Window Phone 7 ( Mango) and if available in hardware, Bada 1.2 & 2.x and webOS. The syntax is:

var watchID = navigator.compass.watchHeading( compassSuccess, compassError, [compassOptions]);

Example

 

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

    <title>Cordova WP7</title>

    <link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title"

        charset="utf-8" />

    <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>

    <script type="text/javascript">

        // The watch id references the current `watchHeading`

        var watchID = null;

        // Wait for Cordova to load      

        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready      

        function onDeviceReady() {

            startWatch();

        }

        // Start watching the compass   

        function startWatch() {

            // Update compass every 3 seconds

            var options = { frequency: 3000 };

            watchID = navigator.compass.watchHeading(onSuccess, onError, options);

        }

        // Stop watching the compass     

        function stopWatch() {

            if (watchID) {

                navigator.compass.clearWatch(watchID);

                watchID = null;

            }

        }

        // onSuccess: Get the current heading    

        function onSuccess(heading) {

            var element = document.getElementById('heading');

            element.innerHTML = 'Heading: ' + heading.magneticHeading;

        }

        // onError: Failed to get the heading       

        function onError(compassError) {

            alert('Compass error: ' + compassError.code);

        }

    </script>

  </head>

  <body>

    <div id="heading">Waiting for heading...</div>

    <button onclick="startWatch();">Start Watching</button>

    <button onclick="stopWatch();">Stop Watching</button>

  </body>

</html>


3) compass.clearWatch

This method is used to stop watching the compass referenced by the watch ID parameter; watchID is returned by compass.watchHeading. The supported platforms are Android, iPhone, Window Phone 7 (Mango) and if available in hardware, Bada 1.2 & 2.x and webOS. The syntax is:

navigator.compass.clearWatch(watchID);

compassHeading :  A compassHeading object is returned to the compassSuccess callback function when an error occurs. The properties of this method is:

magneticHeading : Heading in degrees from 0-359.99 at a single moment in time.
trueHeading : The heading relative to the geographic north pole in degrees 0-359.99 at a single moment in time.
headingAccuracy : The deviation in degrees between the reported heading and the true heading.
timestamp : The time at which this heading was determined.

Summary : In this article I explained the various methods of campass in Apache Cordova/PhoneGap.


 

COMMENT USING

Trending up