Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude).
One specific requirement is to find drivers who are within a 200-meter distance from the user's current position. To achieve this, I implemented the following method in the driver schema:
driverSchema.methods.CloseDriver = function (userCurrentPosition,next) {
try {
const distance = geolib.getPreciseDistance(
userCurrentPosition,
this.currentPosition
);
return distance <= 200
} catch (error) {
return next();
}
}
After defining this method, I handle a POST request containing the user's currentPosition as follows:
const parsedBody = Object.setPrototypeOf(req.body, {});
if(parsedBody.hasOwnProperty("latitude") && parsedBody.hasOwnProperty("longitude")){
const { latitude , longitude } = req.body
const currentPosition = { latitude , longitude }
const drivers = await Driver.find({})
const eligibleDrivers = drivers.filter((driver)=> driver.CloseDriver(currentPosition))
return res.status(200).json({
status : 200 ,
eligibleDrivers
});
In case we have a large array of drivers, is there a more efficient way to accomplish this task?