I'm trying to build a small project where I have a list of places and I can filter them according to a quantity x of km. Ex: Filter all places within a 5km radius of my current location.
I have Json
with some places in my city and when I try to make a 2km filter the Json
returns blank, but if I pass 50km as a parameter all data is returned. I can not figure out where I'm going wrong.
Here's some code snippet:
var mongoose = require('mongoose');
var Location = mongoose.model('Location');
// create an export function to encapsulate the controller's methods
module.exports = {
index: function(req, res, next) {
res.json(200, {
status: 'Location API is running.',
});
},
findLocation: function(req, res, next) {
var limit = req.query.limit || 10;
// get the max distance or set it to 8 kilometers
var maxDistance = req.query.distance || 8;
// we need to convert the distance to radians
// the raduis of Earth is approximately 6371 kilometers
maxDistance /= 6371;
// get coordinates [ <longitude> , <latitude> ]
var coords = [];
coords[0] = req.query.longitude || 0;
coords[1] = req.query.latitude || 0;
// find a location
Location.find({
loc: {
$near: coords,
$maxDistance: maxDistance
}
}).limit(limit).exec(function(err, locations) {
if (err) {
return res.json(500, err);
}
res.json(200, locations);
});
}
};
This is the Json
I'm using:
[
{
"name": "Igreja Matriz",
"loc": [
-49.974762,
-23.160631
]
},
{
"name": "Prefeitura Jacarezinho",
"loc": [
-49.973597,
-23.159745
]
},
{
"name": "Lotérica",
"loc": [
-49.980461,
-23.164231
]
}
]
I pass the parameters by QueryString
as follows: http://localhost:3000/api/locations?longitude=-49.978440&latitude=-23.169557&distance=2
How do I get the desired result?