Make Your Own Compass with the Device Orientation API

Recently, while exploring the world of modern web APIs, I stumbled on the DeviceOrientation API which allows you to determine the exact position and rotation of a device, providing it actually has these sensors. This is especially useful when building mobile apps with technologies like Cordova/Phonegap because they allow access to functionality which would otherwise only be accessible through native applications. But it’s also useful in websites on occasions.

To explore this API further I decided to make a little compass application. We’ll explore a few parts of how it’s been built and provide a demo (for if you’re reading this on your mobile).

2016-04-13 20.26.46

View Demo

How to:#

To get information on the device position, we first setup a listener to be called on any device orientation events.

window.addEventListener(
    "deviceorientation", 
    handler
    true
);

When these events are called, we want to listen for them and call our handler function. This function will have the DeviceOrientationEvent passed into it. This event contains more than just it’s position relative to north, but also the other two axis. This means you have also see how the device is being tilted.

function handler(event) {
    var deg = parseInt(event.alpha);
    $('.arrow')
        .css('-webkit-transform','rotate('+deg+'deg)')
        .css('transform','rotate('+deg+'deg)');
}

In our handler, we process the event’s alpha data and round it to a whole int. Using this degree, we can move our arrow on our page to illustrate the actual position to north.

<div class="arrow">North</div>

View Demo

Here’s some more info on working with device orientation: MDN

Can you think of any other existing uses for this API? Let us know in the comments.