My goal is to calculate the distance between two sets of latitude and longitude coordinates using the npm geolib library. I have a function that queries Firestore and retrieves an array of objects. Within this array, I iterate through each object in a for loop and use the geolib.getPreciseDistance
method to calculate the distance.
The challenge I am facing is sorting the resulting array from the for loop. Ideally, I would like the new array to be sorted with the object closest in distance at index[0].
I have included my current progress below. Any feedback or guidance would be greatly appreciated as I continue to learn. Thank you!
function getNearestWalk() {
let currentLng = userLocation.longitude;
let currentLat = userLocation.latitude;
firestore()
.collection('Walks')
.where('status', '==', 'started')
.limit(10)
.get()
.then((walks) => {
const walksArray = [];
walks.forEach((liveWalks) => {
walksArray.push(liveWalks.data());
});
console.log(walksArray);
for (var i = 0; i < walksArray.length; i++) {
geolib.getPreciseDistance(
{ latitude: currentLat, longitude: currentLng },
{
latitude: walksArray[i].latitude,
longitude: walksArray[i].longitude,
}
);
}
});
}