Reputation: 117
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.
Upvotes: 3
Views: 7940
Reputation: 625
REFERENCES
Upvotes: 9
Reputation: 108
If you need to take the distance between streets and roads, you can use the following lib.
This lib has a callback onReady that contains the returns of distance and duration time.
Upvotes: 2
Reputation: 2686
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;
}
Upvotes: 6