我想获取从当前位置到目的地的距离。我的 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;
最佳答案
今天我遇到了同样的问题,我发现,如果您使用物理设备在“办公室内”执行测试,GPS 定位器可能会受到墙壁等外部事物的干扰,或者受到原因很简单,您尝试在“室内”执行此操作,并且通常应该在室外执行此操作。
我的建议是:尝试使用将 enableHighAccuracy 设置为 true
进行地理定位,如果此操作因位置请求超时错误而失败(在办公室中此可能会失败),使用 false
重试,这应该有效,在我的例子中它确实有效。
希望这对您有帮助。
关于reactjs - 在 React Native 中计算距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50636284/