在 React-Native 中制作指南针

Make compass in React-Native

我正在尝试制作一个指南针,但我不知道如何使用磁力计的数据。

这是我的class罗盘:

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>
    );
  }
}

这是 class 应用:

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>
    );
  }
}

使用此代码,箭头会旋转,但不会按应有的方式旋转。我必须做什么?

这些数字仅与当前检测到的 "magnetic north" 有关,后者受到建筑物中任何 material 铁(如钢)的影响。所以你首先必须确定真正的北方是什么。

您还需要使用 X、Y 和 Z 并获取相对于 phone 的方向(如果它是水平或垂直放置的,以及纵向或横向)。算法一点都不简单。

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

如果您的 React Native 应用程序与 Expo 一起使用,例如它是使用 Create React Native App 命令 (CRNA) 创建的,那么您可以使用 Expo Location。这是 [一个示例](https://github.com/martincarrera/expo-location-example on Github) and here are the docs(查找标题部分)。

否则,您可以使用 React Native simple compass

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

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