Monday, July 2, 2012

PGCompass: PhoneGap Compass

It is very easy to read the compass device in PhoneGap. When you combine it with a png file and a bit of CSS3 you can quickly build a nice looking compass similar to that built in on the iPhone and other devices.

All of the magic of the compass is contained one simple function:

watchId = navigator.compass.watchHeading(success, error, [options])

This call sets up two functions, one to receive a successful callback, the other to receive an error callback, and finally some options, the only one truly supported is the frequency in milliseconds.


If the call is successful it passes back a heading object. It can contain several properties:

  • magneticHeading
  • trueHeading
  • headingAccuracy
  • timestamp

The property that we are interested in is the magneticHeading. While trueHeading may seem more attractive it is not support on Android, so I choose not to use it. 

In the example code, I implement publisher/subscriber pattern for handling the success callback. It may be a bit of overkill, but I like the separation of concerns it gives me. One listener handles the updating of the degree text, the other rotating the compass face. This is accomplished using a CSS3 transform on the <img> tag holding the compass face.

One thing that we should do, but are not is to stop the watcher. This is relatively easy to do. The watchId that is returned from the watchHeading method is simply passed to another method:

navigator.compass.clearWatch(watchId);

This will turn off the listener. That is it for this quick tutorial. The code is on GitHub. Next up everyones favorite device, the camera. I will show how to take a picture and manipulate the image in PhoneGap. Until then, happy coding.

PGCompass Source Code on GitHub


No comments:

Post a Comment