Rails、mapbox 和地理编码器:在另一个对象附近查找对象

Rails, mapbox and geocoder : find object near another object

我尝试根据位置在对象@school 附近找到对象@center,并在 mapbox 上显示中心。我在这里传递我的代码是因为我不确定我做了什么:

这是显示地图的代码(有 2 个数据:学校和中心):

<div id="school-map" data-coordinates="<%= @school.coordinates.reverse %>" data-centers="<%= @center.coordinates.reverse %>"> </div>

这是 center.rb 模型:

class Center
  include Mongoid::Document
  include Geocoder::Model::Mongoid

  has_many :schools
  accepts_nested_attributes_for :schools

  field :title,             type: String

  field :image_path,        type: String
  field :Attachment_path,   type: String
  field :website,           type: String

  field :phone,             type: String

  field :street,            type: String
  field :zipcode,           type: String
  field :city,              type: String
  field :coordinates,       type: Array

  geocoded_by :adress
  #after_validation :geocode

  def adress
    [street, zipcode, city].compact.joint(', ')
  end

end

在school.rb模型中,我尝试了这个方法:

   def center_near_school(school_adress_coordinates)
school_adress_coordinates = @school.coordinates.reverse
center = Center.near(school_adress_coordinates, 1, units: :km)

结束

我尝试显示 "yes" 或 "no" 之类的字符串以了解我的方法是否有效:

<% if @school.center_near_school %>
            <p> OUI </p>
          <% else %>
            <p> NON </p>
          <% end %>

我在两个模型中创建关系(has_many:学校,has_many:中心),标记生成在显示地图的show.js中创建。

有人可以帮我找到一些创建此功能的解决方案吗?

不要犹豫,让我编辑此 post 以提供更多信息(代码、精度 ...)

谢谢!

Center.near(school_adress_coordinates, 1, units: :km)

returns一个中心数组,如果没有找到中心可以为空

您的方法应称为 centers_near_school,您可以使用:

<% if @school.centers_near_school.empty? %>
  <p> NON </p>
<% else %>
  <p> OUI </p>
<% end %>

在Ruby中,每个对象都是"truthy",除了falsenil。即使是空数组在 if 语句中也被认为是真的。