2017-08-18 58 views
0

我正在构建一个存储位置(以及它们的坐标)的API,并且我想根据它们与用户的距离来查询它们。nodejs:计算从位置到用户的距离

在我的视图控制器,我有这样的代码:

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); 
     } 

即返回用户当前位置。 我的模式是仿照这样的:

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], 
    }, 

而且在我APIcontroller,我试图做到这一点:

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);  
    }; 
} 

我提交的最小和最大距离是这样的:

<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> 

但没有任何反应。我得到0个结果。我究竟做错了什么? 另外,我如何计算用户和位置之间的距离,并返回每一行?

回答