I'am trying to make a compass but i don't know how to use the data of the Magnetometer.
This is my class Compass:
class Compass extends Component {
constructor(props) {
super(props);
}
componentWillMount(){
this._animeRotation = new Animated.Value(0);
}
componentDidMount() {
this.startAnimation();
}
startAnimation() {
Animated.timing(this._animeRotation, {
toValue: this.props.magn, //<-- What put here?
duration: 1000,
}).start(() => {
this.startAnimation();
});
}
render() {
var interpolatedRotateAnimation = this._animeRotation.interpolate({
inputRange: [0, 100],
outputRange: ['0deg', '360deg']
});
return (
<View>
<Animated.View style={[styles.box, {transform: [{rotate: interpolatedRotateAnimation}]}]}>
<Image style={styles.box} source={require('./arrow.png')}></Image>
</Animated.View>
</View>
);
}
}
This is the class App:
class App extends Component {
constructor(props) {
super(props);
this.state = {
magn: {
x: 0,
y: 0,
z: 0
}
};
}
componentDidMount() {
//I can get the gyroscope if is necessary
SensorManager.startMagnetometer(500);
// magn is a object with axis z,y and x
DeviceEventEmitter.addListener('Magnetometer', (magn) => this.setState({magn}));
}
render() {
return (
<View>
<Compass magn={this.state.magn.x}></Compass>
</View>
);
}
}
With this code the arrow rotate but not as it should. That I have to do?
Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.
The numbers are just relative to currently detected "magnetic north" which is affected by any material with iron (like steel) in the building. So you first have to determine what the true north is.
Also you need to use the X, Y, and Z and get the direction relative to the phone (if it's held horizontally or vertically and which way portrait or landscape). The algorithm is not simple at all.
For this reason, I suggest you use existing packages for getting the direction instead of the Sensor data package. They do the calculations and give you a number with the heading like you seem to be expecting in your animation code. Another possibility is to look into the open source code of these packages and copy the calculations.
If your React Native app is with Expo, like if it was made with the Create React Native App
command (CRNA) then you can use Expo Location
. Here's [an example](https://github.com/martincarrera/expo-location-example on Github) and here are the docs (look for the Heading section).
Otherwise, you can use the React Native simple compass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With