Answer the question
In order to leave comments, you need to log in
How to make a geoNear request through a mongoose model?
I'm studying the MEAN stack and I can't figure out what the snag is. I'm doing a query on a book query, but 0 results are returned to me. I make a request like: localhost:3000/api/locations?lng=-0.9690884&lat=51... but it doesn't return anything to me. do attributes like maxDistance accept in radians? Is the data conversion to radians correct? Help me to understand. Returns only if I specify the full coordinates that the document has. Below is the code.
API controller:
var Loc = mongoose.model('Location');
var theEarth = (function(){
var earthRadius = 6371; // киллометров или 3959 миль
var getDistanceFromRads = function(rads){
return parseFloat(rads * earthRadius);
}
var getRadsFromDistance = function(distance){
return parseFloat(distance / earthRadius);
}
return {
getDistanceFromRads : getDistanceFromRads,
getRadsFromDistance : getRadsFromDistance
};
})()
module.exports.locationsListByDistance = function(req, res){
if(req.query.lng || req.query.lat || req.quert.maxDistance){
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var maxDistance = parseInt(req.query.maxDistance);
var geoOptions = {
spherical: true,
maxDistance: theEarth.getRadsFromDistance(maxDistance),
num: 10,
};
var point = {
type: "Point",
coordinates: [lng, lat]
}
Loc.geoNear(point, geoOptions, function(err, result, stats){
if(err){
sendJsonResponse(res,404,err);
return;
}else{
console.log(geoOptions);
var locations = [];
result.forEach(function(doc){
locations.push({
distance: theEarth.getDistanceFromRads(doc.dis),
name: doc.obj.name,
address: doc.obj.address,
rating: doc.obj.rating,
facilities: doc.obj.facilities,
_id: doc.obj._id
});
});
sendJsonResponse(res,200,locations);
}
});
}else{
sendJsonResponse(res,404,{'message':'lng and lat is required'});
}
};
var renderHomepage = function(req, res, responseBody){
console.log(responseBody);
res.render('locations-list' ,{
title: 'Home',
pageHeader: {
title: 'Lock8r',
strapline: 'Find places to work with wifi near you!'
},
locations: responseBody,
sidebar: 'Lock8r helps you find places to work when out and about.'
});
}
/* GET 'home' page */
const homelist = function(req, res){
var requestOptions, path;
path = '/api/locations';
requestOptions = {
url: apiOptions.server + path,
method: "GET",
json: {},
qs: {
lng: -0.9690885,
lat: 51.455041,
maxDistance: 1
}
}
request(
requestOptions,
function(err, response, body){
var i, data;
data = body;
for(i=0; i < data.length; i++){
data[i].distance = _formatDistance(data[i].distance);
}
renderHomepage(req, res, data);
}
);
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question