I'm currently working on customizing my REST API to only retrieve items that fall within a specific radius. I have successfully written the code to calculate the distance between two points and filter out items outside the desired range. However, my current implementation uses a predefined latitude and longitude as the reference point. Is there a way for me to integrate my own location into this algorithm?
app.get('/posts', function(req, res) {
// Accessing the 'posts' collection from the database
db.collection('posts', function(err, collection) {
// Retrieving all documents in the 'posts' collection
collection.find().toArray(function(err, items) {
// Array to store filtered documents
var results = []
//Function for calculating distance between two points.
function calculateDistance (lat1, lat2, lon1, lon2) {
var dLat = deg2rad(lat2-lat1);
var dLon = deg2rad(lon2-lon1);
var a =
(Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2))
;
var c = (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
var d = (6371 * c); // Distance in km
var e = (d/1.6) //Converting distance in km to miles.
return e
}
// Iterating over each document and checking the distance criteria
for (var i = 0; i < items.length; i++) {
var item = items[i]
if ((calculateDistance(item.latitude, 43.7035798, item.longitude, -72.2887838) > 25)) {
results.push(item)
}
}
res.send(results);
});
});
});