Thursday, January 29, 2015

PhoneGap plugins: Compass

device-orientation plugin needed.
Install it with this: 

phonegap plugin add org.apache.cordova.device-orientation

Here is my example.html(within javascript code).
This example provides current heading of device and display it into a javascript alert:

<!DOCTYPE html>
<html>
  <head>
    <title>PhoneGap Compass Example Page</title>

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

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function getCurrentHeading() {
        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>PhoneGap Compass Example</h1>
    <p>
        <button onclick="getCurrentHeading()">Click me to get current heading</button>
    </p>
  </body>
</html>


Bye... 

No comments:

Post a Comment