mongoid geo_near 与 max_distance

mongoid geo_near with max_distance

我正在使用 railsmongoid 为移动应用构建 json API,但遇到了一些问题..

我们有一个名为 placescollection,它存储以下内容:

class Place
  include Mongoid::Document
  include Mongoid::Timestamps
  has_many :posts

  field :location,          type: Array
  field :name,         type: String
  field :type_id,      type: String
  field :address,      type: String

  index({location: "2d"})
  index({ name: 1, type_id: 1, address: 1})

end

条目的典型 JSON 视图如下所示:

{
    _id: ObjectId("556cf17f6cac06684b8b456a"),
    address: "406 9th Avenue, San Diego, CA, United States",
    location: [
        -117.1569243,
        32.7096999
    ],
    name: "APP HQ",
    type_id: "custom"
}

我正在尝试将位置拉到特定坐标附近。所以我用邮递员 运行 这个 url:

localhost:3000//v1/places/feed?lat=40.7127&lon=74(坐标是纽约附近的某个地方——所以上面的地方不应该是 returned)

这个returns:

[
    {
        "_id": "556cd5dc4a75730453010000",
        "address": "406 9th Avenue, San Diego, CA, United States",
        "created": 1433195996,
        "created_at": "2015-06-01T21:59:56.403Z",
        "geo_near_distance": 160.5248370906633,
        "location": [
            -117.1569243,
            32.7096999
        ],
        "name": "APP HQ",
        "type_id": "custom",
        "updated_at": "2015-06-01T21:59:56.403Z"
    }
]

所以这是不对的。所以我添加 .max_distance 并提供以米为单位的数字,如下所示:

loc = [params[:lat],params[:lng]]
        resources = Place.geo_near(loc).max_distance(params[:rad].to_i)

设置我的参数 rad=50 return 没什么。但是,将我的查询字符串中的 lat/lon 更改为 return 上方的确切位置:

[
    {
        "_id": "556cd5dc4a75730453010000",
        "address": "406 9th Avenue, San Diego, CA, United States",
        "created": 1433195996,
        "created_at": "2015-06-01T21:59:56.403Z",
        "geo_near_distance": 32.710076318834695,
        "location": [
            -117.1569243,
            32.7096999
        ],
        "name": "APP HQ",
        "type_id": "custom",
        "updated_at": "2015-06-01T21:59:56.403Z"
    }
]

这似乎不对,因为当时我的 geo_near_distance 是我的请求:

localhost:3000//v1/places/feed?user_email=test1@gmail.com&user_token=Q6R4FNs5i3n1-zfQfbp8&lat=-117.1569243&lon=32.7096999&rad=50

与我要查找的位置 100% 相同,因此它应该为 0,因为它距离输入位置 0 米。

所以我在这里很困惑,这里的正确用例是向方法提供距离米,并在输出中提供 return 米距离。我这样做是对的还是我在这里的想法完全超出了我的想法?

我最终让它工作了,这里是执行它的代码:

loc = [params[:lon].to_f,params[:lat].to_f]
md = (0.000621371 * params[:rad].to_i)/3959
resources = Place.geo_near(loc).max_distance(md).spherical

md 将我的 radius 取入 meters 并将其转换为 miles 然后除以地球半径以转换为弧度。