【问题标题】:Search for hotels within a given radius for corresponding objects' locations (Gem Geocoder)搜索给定半径内的酒店以获取相应对象的位置(Gem Geocoder)
【发布时间】:2013-03-10 16:51:13
【问题描述】:

我有 3 张桌子:ObjectsLocationsHotels

每个对象有几个位置,每个位置有几个酒店(默认半径为 20 英里)。

我的模型(稍微简化一下以专注于主要内容)

object.rb

attr_accessible :name

has_many :locations
has_many :hotels

location.rb

attr_accessible :name, :address, :longitude, :latitude

has_many :objects
has_many :hotels

hotels.rb

attr_accessible :name, :address, :longitude, :latitude

has_many :objects
has_many :locations

我想创建一个搜索表单,用户可以在其中输入对象的名称搜索半径

输出应该是所有酒店的列表,这些酒店位于每个位置中心的给定半径内(小于或等于 20 英里),对应于对象。

我想使用Geocoder's gem 方法near,但我不知道如何构建此类任务的控制器层。

【问题讨论】:

  • 不相关的旁注:上面的实体关系图使用了什么工具?
  • 我只使用了 Keynote。我通常会画出每个结构以便更好地理解
  • 谢谢。我不确定,因为它看起来很陌生。干得好。

标签: database ruby-on-rails-3 postgresql geolocation


【解决方案1】:

您希望数据库中的空间查询引擎来执行这些查询,例如MongoDB 或 PostGIS(在 Postgres 中)。我认为您正在寻找的答案会因您使用的答案而异。我用 PostGIS 做这些东西,真的很喜欢。

也就是说,无需空间查询引擎,即可在内部使用 Geocoder 为其提供动力,但效率不高。如果你变得非常大,它会停止运转。看源码的话:https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/stores/active_record.rb

# skeleton for the controller method
obj = Object.find(name)
locations = obj.locations
near_hotels = locations.map do |loc| 
  locations.hotels.near([loc.latitude, loc.longitude])
end

不确定 near 方法是否正确接受半径参数,但您可以通过基本上复制它来轻松编写自己的方法:

# on the hotel class
def nearby(lat, lon, radius)
    options = self.send(:near_scope_options, lat, lon, radius, {})
    select(options[:select]).where(options[:conditions]).
      order(options[:order])
}

我强烈建议您查看 PostGIS。

注意,我的示例方法产生了一个关系。您可以通过将范围限定为与您的对象匹配的酒店来缩小选择范围。

【讨论】:

  • 我知道我做的很晚,但我检查了 Postgis,它非常好。
猜你喜欢
  • 2013-05-06
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多