如何在 React Native Expo 中使用纬度和经度计算两点之间的距离?

How to calculate the distance between two points using latitude and longittude in react native expo?

我实际上正在开发一个小型反应本机应用程序,我需要计算经度和纬度之间的距离。我有我当前位置的经度和纬度,我有目的地的经度和纬度。

我尝试使用 geolib,但它在控制台上不断出现错误: 获取距离时出错“[TypeError: undefined is not an object (evaluating 'P.default.getDistance')]”

这是导致上述错误的组件:

_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 函数就收到错误消息。 任何建议将不胜感激。

这就是我做的,叫做the Haversine formula:

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;
}

如果需要获取街道和道路之间的距离,可以使用下面的lib。

https://github.com/bramus/react-native-maps-directions

此库有一个回调 onReady,其中包含 distance 的 returns 和 duration次.

参考资料

  1. 您需要使用Haversine Formula来计算距离。
  2. 你也可以查看这个package