geokit / geokit-rails

Official Geokit plugin for Rails/ActiveRecord. Provides location-based goodness for your Rails app. Requires the Geokit gem.
MIT License
1.57k stars 245 forks source link

Can we use by_distance with radius option? #143

Closed hcyildirim closed 5 years ago

hcyildirim commented 5 years ago

Hi,

I have places and I want to show places only in 5 km radius and order by distance. Can we do that?

For example, this is what I have:

Location.within(user.visible_distance, :units => user.settings["units"].to_sym, :origin => [lat, lon])

This is what I want: (by_distance method with radius option)

Location.by_distance(user.visible_distance, :units => user.settings["units"].to_sym, :origin => [lat, lon])

Thank you.

hcyildirim commented 5 years ago

I solved my problem with the code below. Is this code looks right?

module Geokit::ActsAsMappable
  module ClassMethods
    def by_distance_with_radius(distance, options = {})
      options[:within] = distance

      origin = extract_origin_from_options(options)
      units = extract_units_from_options(options)
      formula = extract_formula_from_options(options)

      distance_column_name = distance_sql(origin, units, formula)
      bounds = formulate_bounds_from_distance(options, origin, units)

      with_latlng
        .where(bound_conditions(bounds))
        .where(Arel.sql(distance_column_name).lteq(options[:within]))
        .order(Arel.sql(distance_column_name).send(options[:reverse] ? "desc" : "asc"))
    end
  end
end