【问题标题】:Whats the most efficient way to get areas where lat/lng fall under?获取 lat/lng 所在区域的最有效方法是什么?
【发布时间】:2020-07-21 00:48:18
【问题描述】:

area 有很多coordinates coordinate 模型有两个属性:latitudelongitude

还有什么可以重构的吗?现在它可以工作,但它会执行一种 n+1 查询:

areas.each_with_object([]) do |area, array|
  geokit_lat_lngs = area.coordinates.order(sequence: :asc).map do |coordinate|
    Geokit::LatLng.new(coordinate.latitude, coordinate.longitude)
  end

  polygon = Geokit::Polygon.new(geokit_lat_lngs)
  point   = Geokit::LatLng.new(latitude, longitude)
  array << area.id if polygon.contains?(point)
end

我正在尝试获取所有 latitudelongitude 属于的 areas

我正在使用 Geokit gem,但如果我应该做一些更有效的事情,我很乐意切换

【问题讨论】:

标签: ruby-on-rails ruby geokit


【解决方案1】:

根据您的数据库应该包含多少个区域,您可以有不同的策略。

如果你的区域数量比较少,而每个区域的坐标数量也很少,可以preload甚至eager_load将坐标存入内存。

# Suppose `areas` is an `ActiveRecord::Relation`, not just an array
areas.preload(:coordinates).each_with_object([]) do |area, array|
  # Do an in-memory sort
  geokit_lat_lngs = area.coordinates.sort_by(&:sequence).map do |coordinate|
    # ...
  end
end

如果区域的数量大到足以让你记忆犹新,那么也许你目前的方法是最好的方法。顺便说一句,我不熟悉 PostgreSQL 中的地理位置数据类型。

【讨论】:

  • 不幸的是,areascoordinates 都将包含数百条记录。一个城市的区域可以从 20 到 50 不等。坐标更多
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
相关资源
最近更新 更多