2
votes

I'm actually working on a small react native app, I need to calculate the distance between Longitude and Latitude. I have the Longitude and Latitude of my current location and I have the Longitude and Latitude of the destination.

I tried using geolib, but it keep getting an error on console: error in get distance "[TypeError: undefined is not an object (evaluating 'P.default.getDistance')]"

That's the component that causes the error above:

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

I am getting error as soon as i put _getDistanceAsync function. Any suggestions will be greatly appreciated.

3
Actually that's not the same, because i work with node as a backend so that's not working with me.Soufien JAOUADI

3 Answers

7
votes

REFERENCES

  1. You need to use Haversine Formula to calculate distance.
  2. You can also check this package
5
votes

This is what I do, it's called 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;
}
2
votes

If you need to take the distance between streets and roads, you can use the following lib.

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

This lib has a callback onReady that contains the returns of distance and duration time.