Detecting compass support
Open on mobile phone, to view compass example
GPS Hack step 1. Go outside to get GPS signal.
GPS Hack step 2. Go forward to take initialized heading from GPS.

Compass.js allows you to get compass heading in JavaScript. Today we haven’t any standard way to get compass data, but there are two proprietary APIs and one hack:

This library hides all this magic and APIs from you, autodetects available way and provides clean and simple API for your geolocation web app.

Fork me on GitHub
Sponsored by Evil Martians


Hide compass for desktop users (without compass, GPS and accelerometers):

Compass.noSupport(function () {

Show instructions for Android users:

Compass.needGPS(function () {
  $('.go-outside-message').show();          // Step 1: we need GPS signal
}).needMove(function () {
  $('.move-and-hold-ahead-message').show(); // Step 2: user must go forward
}).init(function () {
  $('.move-and-hold-ahead-message').hide(); // GPS hack is enabled

Add compass heading listener: (heading) {
  $('.compass').css('transform', 'rotate(' + (-heading) + 'deg)');

Method Name

Library will detect method asynchronously, so you can’t just read Compass.method, because it can be empty yet. It will be better to use Compass.init method:

Compass.init(function (method) {
  console.log('Compass heading by ' + method);

If library is already initialized, callback will be executed instantly, without reinitialization.


You can remove compass listener by Compass.unwatch method:

var watchID = (heading) {



Ruby on Rails

For Ruby on Rails you can use gem for Assets Pipeline.

  1. Add compassjs gem to Gemfile:

    gem "compassjs"
  2. Install gems:

    bundle install
  3. Include Compass.js to your

    #= require compass


If you don’t use any assets packaging manager (it’s very bad idea), you can use already minified version of the library.

Take it from: