I am constructing a easy compass app utilizing react-native and Expo. I am testing it on my iPhone utilizing Expo Go. I am utilizing knowledge from the Magnetometer
library to calculate heading and show it with an arrow. The arrow doesn’t level north though the inbuilt iPhone compass app factors north simply superb. My arrow additionally modifications instructions considerably after I tilt the cellphone so it is not coplanar with the bottom.
I get the calibrated magnetometer knowledge utilizing import { Magnetometer } from 'expo-sensors';
and Magnetometer.addListener(myCallBackFunc)
. The uncooked sensor knowledge offered is an x, y, and z worth. I take advantage of a easy equation to calculate a heading from the x and y values: Math.atan2(knowledge.y, knowledge.x) * (180 / Math.PI);
What’s the inbuilt compass app doing that I’m not?
const Compass = () => {
const [magnetometerSub, setMagnetometerSub] = useState(null);
const [northAngle, setNorthAngle] = useState(null);
useEffect(() => {
subscribeToMagnetometer();
return () => unsubscribeFromMagnetometer();
}, []);
const subscribeToMagnetometer = () => {
setMagnetometerSub(
Magnetometer.addListener((knowledge) => {
setNorthAngle(calculateNorthAngle(knowledge));
})
);
};
const unsubscribeFromMagnetometer = () => {
magnetometerSub && magnetometerSub.take away();
setMagnetometerSub(null);
setNorthAngle(null);
};
// Calculates North angle from magnetometer studying
// Returns values in levels in vary (-180, 180]
const calculateNorthAngle = (knowledge) => {
if (!(knowledge && knowledge.x && knowledge.y)) {
return null;
}
return Math.atan2(knowledge.y, knowledge.x) * (180 / Math.PI);
};
return (
<View>
{northAngle ? (
// Arrow factors to the precise when angle is 0
<Arrow angle={northAngle.toString()} />
) : (
<Textual content>no angle knowledge</Textual content>
)}
</View>
);
};
machine: iPhone 14 Professional Max,
iOS: 16.6.1,
npm: 9.8.1,
node: 18.18.0,
expo: 49.0.3
PS: I’m testing this in an airport. May that be a supply of magnetic interference?
In that case, why does the inbuilt compass app nonetheless work superb within the airport?