Geolocation 如何利用纬度和经度计算两个点之间的距离?
我正在开发一个小型的react原生应用程序,我需要计算经度和纬度之间的距离。我有我当前位置的经度和纬度,我有目的地的经度和纬度 我尝试使用geolib,但它在控制台上不断出现错误: 获取距离时出错“[TypeError:undefined不是对象(计算'P.default.getDistance')” 这就是导致上述错误的组件:Geolocation 如何利用纬度和经度计算两个点之间的距离?,geolocation,Geolocation,我正在开发一个小型的react原生应用程序,我需要计算经度和纬度之间的距离。我有我当前位置的经度和纬度,我有目的地的经度和纬度 我尝试使用geolib,但它在控制台上不断出现错误: 获取距离时出错“[TypeError:undefined不是对象(计算'P.default.getDistance')” 这就是导致上述错误的组件: _getLocationAsync = async () => { let location = await Location.getCurrent
_getLocationAsync = async () => {
let location = await Location.getCurrentPositionAsync({});
const region = {
latitude: location.coords.latitude,
longitude: location.coords.longitude
}
this.setState({ location, region});
console.log(this.state.region)
/* it displays me on console my current position like this :
"Object {
"latitude": 36.8386878,
"longitude": 10.2405357,
}" */
this._getDistanceAsync();
}
};
_getDistanceAsync = async () => {
try {
const distance = geolib.getDistance({ latitude: 51.5103, longitude:
7.49347 }, this.state.region)
this.setState({ distance });
console.log(this.state.distance)
} catch (error) {
console.log("error in get distance", error)
}
};
我一放入_getDistanceAsync函数就出现错误。
如果您有任何建议,我们将不胜感激。这就是我所做的,它被称为:
如果需要计算街道和道路之间的距离,可以使用以下lib 此库有一个回调onReady,其中包含距离和持续时间的返回。引用
可能的重复事实上这不一样,因为我使用node作为后端,所以这不适用于我。我使用这个包是因为它可以与node js一起工作,并且工作得非常好。谢谢你的帮助,这太棒了。与geolib一样工作,但无需安装新软件包。非常感谢。
function computeDistance([prevLat, prevLong], [lat, long]) {
const prevLatInRad = toRad(prevLat);
const prevLongInRad = toRad(prevLong);
const latInRad = toRad(lat);
const longInRad = toRad(long);
return (
// In kilometers
6377.830272 *
Math.acos(
Math.sin(prevLatInRad) * Math.sin(latInRad) +
Math.cos(prevLatInRad) * Math.cos(latInRad) * Math.cos(longInRad - prevLongInRad),
)
);
}
function toRad(angle) {
return (angle * Math.PI) / 180;
}