【问题标题】:calculating distance in React Native在 React Native 中计算距离
【发布时间】:2018-06-01 04:52:08
【问题描述】:

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

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

【问题讨论】:

标签: reactjs react-native react-android


【解决方案1】:

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

我的建议是:尝试使用设置为 trueenableHighAccuracy 进行地理定位,如果失败并出现 location request timed out 错误(在办公室可能会失败),请重试使用false,这应该有效,在我的情况下它确实有效。

希望这会对你有所帮助。

【讨论】:

  • 我可以计算距离,这很容易。我需要当前位置的经度和纬度。我该怎么做?
  • 比你应该给出的问题标题是,没有使用地理定位 API 获得当前位置。无论如何,您是否尝试过增加超时时间?
  • 是的,我尝试增加超时。还是一样的问题
  • @user54967 我已经更新了答案。我的情况是,上述解决方案有效,我希望它也适用于您。谢谢
  • 我把 enableHighAccuracy =false。我在上面粘贴了我更新的代码。这只发生在android.apple电脑上就好了,
【解决方案2】:

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

创建此库是为了解决 android 上的位置超时问题,使用 react-native 的当前实现 Geolocation API。这个库试图通过使用 Google Play 服务的新 FusedLocationProviderClient API 来解决这个问题,谷歌强烈推荐它而不是 android 的默认框架位置 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2014-08-28
    相关资源
    最近更新 更多