3

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.

Dupocas
  • 20,285
  • 6
  • 38
  • 56
Soufien JAOUADI
  • 119
  • 2
  • 12
  • Possible duplicate of [Calculate distance between two latitude-longitude points? (Haversine formula)](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula) – Dupocas Jul 23 '19 at 15:41
  • Actually that's not the same, because i work with node as a backend so that's not working with me. – Soufien JAOUADI Jul 24 '19 at 11:28

3 Answers3

8

REFERENCES

  1. You need to use Haversine Formula to calculate distance.
  2. You can also check this package
mosabbir tuhin
  • 560
  • 4
  • 14
6

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;
}
Brian Le
  • 2,646
  • 18
  • 28
2

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.

fl3a
  • 108
  • 5