Magnetometer in Mobile Apps: Compass and Heading

Use the magnetometer (compass) to detect the device heading in iOS and Android, with calibration tips and copy-pasteable Expo, Swift and Kotlin code.

Timothy Lindblom

Founder, Newly

The magnetometer measures the local magnetic field — primarily Earth's — on three axes. It is the sensor behind the compass, the heading needle on a map, and any "point me at the nearest X" feature. It is also the noisiest of the motion sensors, because every speaker, magnet and metal frame distorts the field.

Key Takeaways

  • Magnetometer values are in microtesla (µT) on each of three axes.
  • Heading is derived: combine the magnetometer with the accelerometer (or rotation vector) to get a stable compass.
  • Magnetic interference is real — calibrate by asking the user to draw a figure-8 in the air.
  • On iOS prefer Core Location's `CLLocationManager.headingUpdates`; it does the fusion for you.

Magnetometer at a Glance

µT
Microtesla per axis
±50 µT
Earth's field strength
15–50 Hz
Typical sample rate
99%
Smartphone availability

What It Is & How It Works

What it is. A 3-axis Hall-effect or magnetoresistive sensor that measures the local magnetic field vector. Combined with knowledge of which way is "down" (from the accelerometer), the OS can compute true device heading.

How it works. You can subscribe to raw {x, y, z} magnetic field samples or — better — to a fused heading stream that returns degrees from north. Most apps want the fused stream.

Units & signal. Raw samples are in µT. Heading is in degrees, with 0° as magnetic north and 360° as a full turn. iOS Core Location can also give true north using the user's location.

What You Can Build With It

Compass apps

Show a north-pointing needle that rotates as the user turns. The classic magnetometer use case.

Example: A backpacking compass with magnetic and true-north modes.

AR direction indicators

Augment a map view with a heading wedge so the user knows which way they're facing.

Example: A walking-tour app showing arrows toward the next POI.

Astronomy and stargazing

Identify constellations by combining heading with device tilt.

Example: A planetarium app that highlights what's above the device.

Indoor navigation hints

Magnetic anomalies can fingerprint indoor locations when GPS is unavailable.

Example: A mall navigation app that augments BLE beacons with magnetic features.

Permissions & Setup

Reading raw magnetometer samples needs no permission, but Core Location heading on iOS requires location permission so it can compute true north from your latitude. Android does not require any runtime permission.

iOS · Info.plist

  • NSMotionUsageDescription
  • NSLocationWhenInUseUsageDescription (for true north)

Android · AndroidManifest.xml

No special permission keys required.

Code Examples

Setup

  • Expo: `npx expo install expo-sensors`
  • iOS: prefer `CLLocationManager` heading updates over raw `CMMagnetometer`
  • Android: combine `TYPE_MAGNETIC_FIELD` + `TYPE_ACCELEROMETER` via `getRotationMatrix` + `getOrientation`
import { useEffect, useState } from 'react';
import { Magnetometer } from 'expo-sensors';

export function useHeading() {
  const [heading, setHeading] = useState(0);

  useEffect(() => {
    Magnetometer.setUpdateInterval(100);
    const sub = Magnetometer.addListener(({ x, y }) => {
      const angle = (Math.atan2(y, x) * 180) / Math.PI;
      setHeading((angle + 360) % 360);
    });
    return () => sub.remove();
  }, []);

  return heading;
}

Tip: With Newly, you describe the feature you want and the AI agent wires up the sensor, permissions, and UI for you. Try it free.

Best Practices

  • Use the platform heading API when you can

    `CLLocationManager` on iOS and the rotation vector + getOrientation on Android handle calibration and tilt compensation correctly.

  • Show a calibration prompt

    When the system reports low accuracy, ask the user to wave the device in a figure-8 — the standard recalibration motion.

  • Smooth the result

    Use a low-pass filter on the heading degrees so a needle doesn't jitter across 5° on every update.

  • Hide the compass near magnets

    If the magnetic field magnitude is far from 25–65 µT, you are near interference. Surface a "calibrate" hint instead of a wrong heading.

Common Pitfalls

Magnetic interference

Speakers, MagSafe accessories, car dashboards and steel-frame buildings distort readings by tens of degrees.

Mitigation: Check field strength magnitude; alert the user when it falls outside 20–70 µT.

Forgetting tilt compensation

Computing heading directly from atan2(y, x) only works when the device is flat.

Mitigation: Use the rotation matrix (Android `getRotationMatrix`) or `CLHeading` to get a tilt-corrected value.

True vs magnetic north confusion

These differ by up to ~20° depending on where you are on Earth.

Mitigation: Document which one you use; on iOS prefer `trueHeading` (requires location) for navigation.

Battery from polling Core Location heading

Heading updates wake the magnetometer constantly when active.

Mitigation: Stop heading updates when the screen is hidden; use a generous `headingFilter`.

When To Use It (And When Not To)

Good fit

  • Compasses and orientation overlays
  • Map "rotate to heading" features
  • AR direction wedges and waypoint arrows
  • Astronomy / outdoor apps that need cardinal direction

Look elsewhere if…

  • Precise indoor positioning — too noisy on its own
  • Always-on background heading on iOS
  • Detecting motion or rotation rate — that's the gyroscope
  • Replacing GPS for direction of travel — use location course instead

Frequently Asked Questions

Why does my compass spin wildly?

Almost always magnetic interference: a speaker in a phone case, a MagSafe wallet, a metal desk. Move away from metal and ask the user to recalibrate with a figure-8.

Magnetic north vs true north — which should I use?

Show true north for navigation (it matches printed maps), magnetic north for hardware-style compass apps. iOS gives you both via CLHeading.

Do I need location permission to read heading?

On iOS, true heading requires it; magnetic heading does not. On Android, no permission is required for the magnetometer itself.

How accurate is a smartphone compass?

A few degrees in clean conditions, sometimes 10–20° near interference. Always smooth the result and tell the user when it is unreliable.

Build with the Magnetometer on Newly

Ship a magnetometer-powered feature this week

Newly turns a description like “use the magnetometer to compass apps into a real React Native app — permissions, native modules and UI included. Full source code is yours, and you can publish to the App Store and Google Play directly from the dashboard.

Start Building Your App

Want a deeper dive on the underlying APIs? See Expo Sensors, Apple Core Motion and Android sensor framework.

Continue Learning