查询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

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

我不熟悉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::hyp:得到包含CCD_ 2的圆

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

最新更新