Implemention of Compass for mobile web browser using JavaScript.

Rohit Kshirsagar
2 min readApr 9, 2021

--

Today’s devices come with sensor that gather data about the device. For web applications, access to these sensors has grown over time in addition to the browser of various sensor APIs such as the Geolocation API, and the DeviceOrientation Events API.

Generic sensor plays vital role in creating compass for mobile web.

The OrientationSensor

The OrientationSensor has two subclasses:

1. AbsoluteOrientationSensor: reports rotation of device in world coordinates, based on real accelerometer, gyroscope, and magnetometer sensors

2. RelativeOrientationSensor: reports rotation of device relative to a stationary coordinate system, based on real accelerometer and gyroscope sensors

Fusion sensors

An interesting aspect of the API is Fusion sensors. You can think of these as virtual sensors that combine or fuse the data of multiple real sensors into a new sensor that is reliable and robust, or that has filtered and combined the data in such as way that is appropriate for a certain goal.

We’ll see the benefit of this later when we first build a simple compass app using the Magnetometer sensor directly, and then see how we can improve this based on the AbsoluteOrientationSensor, a fusion sensor which combines data from real magnetometer, accelerometer, and gyroscope sensors.

How it works?

1. Create sensor

let sensor = new AbsoluteOrientationSensor();

2. Check Absolute Orientation Support

Check Absolute Orientation support

if ( ‘AbsoluteOrientationSensor’ in window ) {

}

3. Define callback function

let sensor = new AbsoluteOrientationSensor();

sensor.addEventListener(‘reading’, listener)

function listener() {

}

4. Heading

Based on the heading, a simple compass image or a map could be rotated to that heading

heading = Math.atan2(2*q[0]*q[1] + 2*q[2]*q[3], 1–2*q[1]*q[1] — 2*q[2]*q[2])*(180/Math.PI);
var headingAdjusted = 270 + heading;
compass.style.Transform = ‘rotate(‘ + headingAdjusted + ‘deg)’;

5. Start sensor

sensor.start();

6. Stop sensor

sensor.stop();

Here is demo link

You can combine geoloction sensor
Geolocation Sensor
JavaScript supplies an API, the Geolocation API, that gives us a way to get, among other things, Latitude and Longitude.

Geolocation.getCurrentPosition(): Retrieves the device's current location, Latitude and Longitude.

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
//navigator.geolocation.watchPosition(geoSuccess);
} else {
alert(“Geolocation is not supported by this browser.”);
}
}

See below js code snippet to check implementation of compass with geolocation sensor

Thanks!

--

--