How to create the Compass?

■ Summary

- Deviceorientation is virtual sensor using accelerometer, gyroscope, magnetic sensor.
So if you want to use the Compass, your target should support the accelerometer, gyroscope, magnetic sensor.
function angleFromRotation(value) {
    var angle = -value % 360;

    if (angle < 0) {
        angle += 360;
    }
    return angle;
}

function onDeviceOrientation(eventData) {
    var angle = eventData.alpha,
        lastAngle = angleFromRotation(rotation),
        deltaAngle = 0,
        text = '';

    // Check if the angle has changed since the last measurement.
    if (isNaN(angle) || angle === lastAngle) {
        return;
    }

    // find direction from given angle
    if (angle < 68 || angle > 292) {
        text = 'NORTH';
    } else if (angle > 112 && angle < 248) {
        text = 'SOUTH';
    }
    
    if (angle > 22 && angle < 158) {
        text += 'EAST';
    } else if (angle > 202 && angle < 338) {
        text += 'WEST';
    }

    // Calculate the rotation of the compass.
    deltaAngle = lastAngle - angle;
    if (deltaAngle > 180) {
        rotation -= 360 - deltaAngle;
    } else if (deltaAngle < -180) {
        rotation += 360 + deltaAngle;
    } else {
        rotation += deltaAngle;
    }

    // Update the direction and angle labels.
    directionEl.innerHTML = text;
    angleEl.innerHTML = Math.round(angle) + '<sup>o</sup>';
    
    // Rotate the compass image.
    rotationEl.style['-webkit-transform'] ='rotate(' + rotation + 'deg)';
}

window.addEventListener('deviceorientation', onDeviceOrientation, false);

Responses

0 Replies