2

我想获得从我当前位置到目的地的距离。我的 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;

我只想获取从当前位置到目的地的距离(以英里为单位)。我怎样才能做到这一点?下面是屏幕以及在此处输入图像描述我收到的错误:

4

2 回答 2

2

添加另一个答案作为解决问题的最佳方法。作为location timeout issue我使用react-native-geolocation-service的解决方案,它就像一个魅力。

创建这个库是为了使用 react-native 的当前实现来修复 android 上的位置超时问题Geolocation API。这个库试图通过使用 Google Play Service 的 new 来解决这个问题FusedLocationProviderClient API,Google 强烈建议使用它而不是 android 的默认框架位置 API。

于 2018-10-29T11:37:16.980 回答
2

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

我的建议是:尝试使用设置为 的enableHighAccuracytrue进行地理定位,如果由于位置请求超时错误而失败(在办公室这可能会失败),请使用 重试false,这应该可以,在我的情况下它确实有效。

希望这会帮助你。

于 2018-06-01T05:06:44.690 回答