I'm building an API that stores locations (with their coordinates), and I want to query them based on their distance to the user.
In my view controller, i have this code:
var geolocation = angular.module('geolocation', []);
navigator.geolocation.watchPosition(render);
var lat, lon = 0;
function render(pos) {
lat = pos.coords.latitude;
lon = pos.coords.longitude;
console.log(lat +","+ lon);
}
That returns the user current position. My schema is modeled like this:
var LocationSchema = new Schema({
locationName: {
type: String,
Required: 'Enter the name of the location.'
},
description: {
type: String,
Required: 'Enter the description of the location.'
},
geolocation: {
type: { type: String, default:"Point" },
coordinates: [Number],
},
And in my APIcontroller, i tried to do this:
exports.find_all_locations_near = function(req, res) {
Location.find({
geolocation:
{
$near :
{
$geometry: { type: "Point", coordinates: [ lat, lon ] },
$minDistance: req.body.minDistance,
$maxDistance: req.body.maxDistance
}
}
}), function(err, location) {
if (err)
res.send(err);
else if (location =='')
//res.json({ message: 'No location was found.' });
console.log('No location was found.');
else
res.json(location);
};
}
I'm submitting the min and max distances this way:
<div class="form-group">
<label>Min Distance</label> <input type="text" class="form-control text-center" ng-model="formData.minDistance"><br>
</div>
<div class="form-group">
<label>Max Distance</label> <input type="text" class="form-control text-center" ng-model="formData.maxDistance"><br>
</div>
But nothing happens. I get 0 results. What am I doing wrong? Also, how can i calculate the distance between the user and a location and return that on each row?