Search code examples
ruby-on-railsrubymapboxrails-geocoder

Rails, mapbox and geocoder : find object near another object


I try to find an object @center near an object @school depending the location, and show the center on mapbox. I past my code here because I'm not sure of what I did :

here is the code displaying map (with 2 data : school and center) :

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

here is the center.rb model :

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

In school.rb model, I try this method :

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

end

and I try to show string like "yes" or "no" to know if my method work :

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

I create relation (has_many :schools, and has_many :centers) in both models, the markers generations are created in show.js which displaying the map.

Does someone could help me to find some solutions to create this functionality ?

Don't hesitate to ask me to edit this post with more informations (code, precisions ...)

thank !


Solution

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

    returns an Array of Centers, which can be empty if no Center is found.

    Your method should be called centers_near_school, and you could use :

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

    In Ruby, every object is "truthy", except false and nil. Even an empty Array is considered to be true in an if statement.