查询包含给定点的所有圆形区域的Mongoid

时间:2015-11-01 15:09:53

标签: ruby mongoid

假设我有两个班级:

class Cirle
  include Mongoid::Document

  field :lat, type: Float
  field :lon, type: Float
  field :radius, type: Integer

end


class Point
  include Mongoid::Document

  field :lat, type: Float
  field :lon, type: Float
end

如何找到包含给定点的所有圆圈?

1 个答案:

答案 0 :(得分:0)

我不熟悉Mongoid,但也许以下内容会有所帮助。假设:

circles = [
  { x: 1, y: 2, radius: 3 },
  { x: 3, y: 1, radius: 2 },
  { x: 2, y: 2, radius: 4 },
]

point = { x: 4.5, y: 1 }

然后在Math::hypot

的帮助下获得包含point的圈子
circles.select { |c|
  Math.hypot((c[:x]-point[:x]).abs, (c[:y]-point[:y]).abs) <= c[:radius] }
  #=> [{ x: 3, y: 1, radius: 2 }, { x: 2, y: 2, radius: 4 }]

编辑:提高效率@Drenmi建议:

x, y = point.values_at(:x, :y)
circles.select do |c|
  d0, d1, r = (c[:x]-x).abs, (c[:y]-y).abs, c[:radius]
  d0*d0 + d1*d1 <= r*r
end