在React-Native中制作指南针

Make compass in React-Native

本文关键字:指南针 React-Native      更新时间:2023-09-26

我想做一个指南针,但我不知道如何使用磁力计的数据。

这是我的类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>
    );
  }
}
这是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>
    );
  }
}

在这段代码中,箭头旋转但不像它应该的那样。我必须这么做吗?

这些数字只是相对于目前检测到的"磁北",它受到建筑物中任何含铁(如钢)材料的影响。所以你首先要确定什么是真北。

你还需要使用X, Y和Z键,并获得相对于手机的方向(如果它是水平或垂直持有,哪个方向是纵向或横向)。这个算法一点也不简单。

出于这个原因,我建议您使用现有的包来获取方向,而不是传感器数据包。他们做计算,并给你一个数字与标题,就像你似乎期望在你的动画代码。另一种可能性是查看这些包的开放源代码并复制计算。

如果你的React Native应用程序是与Expo,如果它是用Create React Native App命令(CRNA),那么你可以使用Expo Location。这里是[一个例子](https://github.com/martincarrera/expo-location-example在Github上),这里是文档(寻找标题部分)。

否则,你可以使用React Native的简单指南针

我最终制作了自己的包。查看一下:

https://github.com/firofame/react-native-compass-heading