nodejs:计算从位置到用户的距离

时间:2017-08-18 02:44:36

标签: angularjs node.js mongoose geojson

我正在构建一个存储位置(及其坐标)的API,我想根据它们与用户的距离来查询它们。

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

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

在我的API控制器中,我试图这样做:

  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结果。我究竟做错了什么? 另外,我如何计算用户和某个位置之间的距离并将其返回到每一行?

1 个答案:

答案 0 :(得分:0)

请注意,在存储坐标时,应先经度然后经纬度。如果这看起来令人困惑,you could store the coordinates as an embedded document也会使用lng&amp; lat

Querying GeoJson Data

相关问题