如何在react native expo中使用纬度和经度计算两点之间的距离?

Sou*_*ADI 2 geolocation

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

我尝试使用 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)
    }
  };
Run Code Online (Sandbox Code Playgroud)

我一放置 _getDistanceAsync 函数就会出错。任何建议将不胜感激。

mos*_*hin 7

参考

  1. 您需要使用Haversine 公式来计算距离。
  2. 你也可以检查这个


Bri*_* Le 5

这就是我所做的,它被称为Haversine公式

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;
}
Run Code Online (Sandbox Code Playgroud)