I'm building a simple API that stores locations with coordinates, and I want to query the locations based on their distance to the user's position.
Right now, I get users position with:
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);
}
And i try to query the locations with:
exports.find_all_locations_near = function(req, res) {
const $minDistance = req.query.minDistance;
const $maxDistance = req.query.maxDistance;
if ($minDistance > 0)
{
Location.find({
geolocation:
{
$near:
{
$geometry:
{
type: "Point",
coordinates: [lat, lon]
},
$minDistance,
$maxDistance
}
}
}), function(err, location) {
if (err) {
//console.log(err);
res.send(err);
}
else if (location =='')
//res.json({ message: 'No location was found.' });
res.json({ message: 'No location was found.' });
else
{
res.json(location);
res.json({ message: 'The end.' });
}
};
} else
{
Location.find({}, function(err, location) {
if (err)
res.send(err);
res.json(location);
res.json(req.params.minDistance);
});
}
}
I'm displaying the results like this:
<tr ng-repeat="search in searchLocations | orderBy:sortType:sortReverse">
<td>{{ search.locationName }}</td>
<td>{{ search.distance}}</td>
</tr>
How do I query the locations with the calculated distance? And how can I make the query work properly, since I'm getting connection refused?
The github repo in case you need more info https://github.com/supermonteiro/geolocationAPI