【问题标题】:$geoNear distance.calculated not working?$geoNear distance.calculated 不起作用?
【发布时间】:2017-01-11 13:44:21
【问题描述】:

我想检索 20 公里半径内的值,但我也得到了 20 公里以外的值。我做错了什么?

var gquery = [{ $geoNear:  {      near: {
                            type: "Point",
                            coordinates: [  -73.935242,40.730610]
                            },
                            $minDistance: 0,
                            $maxDistance: 20000,
                            distanceField: "dist.calculated",
                            spherical: true
                          }},

                          {$group:{_id:'$category', total:{$sum:1}}

                      }];

                          Experiences.aggregate(gquery,
                            function(err, result) {
                              console.log(result);
                            });

【问题讨论】:

    标签: javascript mongodb mongoose geolocation geospatial


    【解决方案1】:

    $maxdistance 找不到以公里为单位的坐标,而是以 弧度 度为单位。因此,您必须将半径换算成 radians 度数。

    例如这样。

    var radius = 20
    var maxDistance = radius / 111.12;
    
    Place.find({
      'loc': {
        $near:[-73.935242,40.730610],
        $maxDistance: maxDistance
      }
    }).exec()
    .then(...)
    

    编辑:这是度数和二维圆

    编辑 2:好吧,我好像在给你 2d 的答案。我很抱歉。

    在 $geoNear 聚合的 Documentation 中说:

    以米为单位为 GeoJSON 数据指定距离,以弧度为单位指定 旧坐标对。

    既然你告诉我你没有使用 GEOJSON,所以在这种情况下你必须将米转换为弧度。

    将公里转换为弧度很简单,只需将其除以地球半径(6371 公里)

    它应该是这样的:

    var radiusInKm = 20
    var radians = radiusInKm / 6371 // Divided by earth radius in kilometers
    
    var gquery = [{
            $geoNear: {
                near: {
                    type: "Point",
                    coordinates: [-73.935242, 40.730610]
                },
                $minDistance: 0,
                $maxDistance: radians,
                distanceField: "dist.calculated",
                spherical: true
            }
        },
    
        {
            $group: {
                _id: '$category',
                total: {
                    $sum: 1
                }
            }
    
        }
    ];
    
    Experiences.aggregate(gquery,
        function(err, result) {
            console.log(result);
        });
    

    【讨论】:

    • 好的,111,12的值是多少还是只是一个例子?
    • 这就是你如何转换它
    • 好的,谢谢,但我正在使用聚合功能,我尝试使用它,但它不适用于您的示例
    • 您使用的是 GEOJson 还是旧版坐标?我假设您使用的是坐标。 Heres $GeoNear 中 maxDistance 的描述,它说:可选。文档可以到的中心点的最大距离。 MongoDB 将结果限制在距中心点指定距离内的那些文档。为 GeoJSON 数据指定距离(以米为单位),为旧坐标对指定以弧度为单位的距离。
    • 另外,您是在一个球体中还是在一个圆圈中搜索。我意识到那是 2d 和 3d 不同的。
    猜你喜欢
    • 2017-07-18
    • 2016-12-16
    • 2015-11-18
    • 2017-09-05
    • 2014-05-02
    • 2021-06-20
    • 2012-10-28
    • 2021-03-26
    • 2011-10-06
    相关资源
    最近更新 更多