在 React-Native 中制作指南针

Posted

技术标签:

【中文标题】在 React-Native 中制作指南针【英文标题】:Make compass in React-Native 【发布时间】:2016-10-30 21:18:20 【问题描述】:

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

这是我的班级指南针:

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

使用此代码,箭头会旋转,但不会旋转。我必须做什么?

【问题讨论】:

【参考方案1】:

这些数字只是相对于当前检测到的“磁北”,它受到建筑物中任何含铁材料(如钢)的影响。因此,您首先必须确定真正的北方是什么。

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

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

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

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

【讨论】:

我还没有找到可以在横向模式下工作的指南针包,特别是在 android 上。有知道的可以分享给我吗?【参考方案2】:

我最终制作了自己的包裹。看看吧:

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

【讨论】:

不错!这适用于 react-native 0.60 吗?有哪些已知错误? @TIMEX 我在我的应用程序中使用 react-naive 0.60.5。目前还没有任何已知的错误,如果发现任何问题,请随时添加。 它比像素 2 滞后很多 这个包滞后很多。不要获得流畅的体验。

以上是关于在 React-Native 中制作指南针的主要内容,如果未能解决你的问题,请参考以下文章

一份React-Native学习指南-感谢分享

在 react-native 中迭代 JSON 数组

整理了一份React-Native学习指南

React JS和React-Native学习指南

React JS和React-Native学习指南

整理了一份React-Native学习指南(转)