【问题标题】:nodejs: calculate distance from location to user [duplicate]nodejs:计算从位置到用户的距离[重复]
【发布时间】:2018-01-26 14:43:30
【问题描述】:

我正在构建一个存储位置(及其坐标)的 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], 
  },

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

【问题讨论】:

    标签: angularjs node.js mongoose geojson


    【解决方案1】:

    请注意,在存储坐标时,经度应该在前,然后是纬度。如果这看起来令人困惑,you could store the coordinates as an embedded document 也可以使用 lng 和 lat 等键。

    Querying GeoJson Data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2012-05-27
      相关资源
      最近更新 更多