reactjs - 在 React Native 中计算距离

标签 reactjs react-native react-android

我想获取从当前位置到目的地的距离。我的 JSON 文件中确实有目的地的经度和纬度。如何获取当前位置的经度和纬度,以便计算两点之间的距离?我在我的 Android 模拟器中尝试了下面的代码,但我不断遇到超时问题。

    import React, { Component } from 'react';
import { View, Text } from 'react-native';

class GeolocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
    );
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

export default GeolocationExample;

我只想获取从当前位置到目的地的距离(以英里为单位)。我怎样才能做到这一点?下面是带有错误 enter image description here 的屏幕我得到的是:

最佳答案

今天我遇到了同样的问题,我发现,如果您使用物理设备在“办公室内”执行测试,GPS 定位器可能会受到墙壁等外部事物的干扰,或者受到原因很简单,您尝试在“室内”执行此操作,并且通常应该在室外执行此操作。

我的建议是:尝试使用将 enableHighAccuracy 设置为 true 进行地理定位,如果此操作因位置请求超时错误而失败(在办公室中此可能会失败),使用 false 重试,这应该有效,在我的例子中它确实有效。

希望这对您有帮助。

关于reactjs - 在 React Native 中计算距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636284/

相关文章:

reactjs - ReactJS 中默认导出的重要性是什么

react-native - 当 RN 屏幕变化时(调用导航时)监听的钩子(Hook)

ios - 如何在 Xcode 的 AppDelegate.h 中声明接口(interface)?

ios - React Native 0.40.0 : RCTBundleURLProvider. h” 找不到文件 - AppDelegate.m

javascript - Metro Bundler 遇到内部错误,请检查您的终端错误输出以获取更多详细信息

reactjs - 节点 : move files in create-react-app template to root post-install

reactjs - Material DateTimePicker onChange Typescript 不匹配错误

reactjs - React 16中具有功能组件的HOC和渲染 Prop

react-native - 无法加载此错误 : . android/repositories.cfg

javascript - undefined 不是 React Native 对象