PhongGap: Rotate image using Compass or Phone Position


compass.html

<!DOCTYPE html>
<html>
<head>
    <title>PhongGap</title>
</head>
<body>

<div data-role="page" id="compass-page">
    <div>
        <img src="images/compassneedle.png" id="needle"/>
    </div>

    <div data-role="footer" data-position="fixed">
        <div data-role="navbar">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="map.html">Map</a></li>
                <li><a href="compass.html" class="ui-btn-active">Compass</a></li>
            </ul>
        </div>
    </div>

    <script type="text/javascript" charset="UTF-8" src="scripts/jQueryRotateCompressed.2.2.js"></script>
    <script type="text/javascript" charset="UTF-8" src="scripts/compass.js"></script>
</div>

</body>
</html>

compass.js


// get called when clicked on compass.html link
$(document).delegate("#compass-page", 'pageinit', function (event) {
    onCompassLoad();
});

function onCompassLoad(){
    console.log('onCompassLoad');
    var options = {frequency: 500}; // rotateNeedle will fire at every 500ms
    navigator.compass.watchHeading(rotateNeedle, compassError, options);
}

function rotateNeedle(degree){
    console.log('rotateNeedle: ' + JSON.stringify(degree));
    // sample content of variable 'degree':
    // {"magneticHeading":138.59375,"trueHeading":138.59375,"headingAccuracy":0,"timestamp":1350667862515}
    // 'magneticHeading' is a heading relative to the magnetic poles of the Earth;
    // 'trueHeading' is a heading relative to the actual North and South Poles of the Earth (around which the planet rotates)
    $('#needle').rotate(degree.magneticHeading);
}

function compassError(err){
    alert('code: ' + err.code + '\n' + 'message: ' + err.message);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s