Class: Mongoid::Contexts::Mongo

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid_spacial/contexts/mongo.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#geo_near(center, opts = {}) ⇒ Array

Fetches rows from the data base sorted by distance. In MongoDB versions 1.7 and above it returns a distance. Uses all criteria chains except without, only, asc, desc, order_by

Examples:

Minimal Query


Address.geo_near([70,40])

Chained Query


Address.where(:state => 'ny').geo_near([70,40])

Calc Distances Query


Address.geo_near([70,40], :max_distance => 5, :unit => 5)

Parameters:

  • center (Array, Hash, #to_lng_lat)

    The center of where to calculate distance from

  • opts (Hash) (defaults to: {})

    the options to query with

Returns:

  • (Array)

    Sorted Rows



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/mongoid_spacial/contexts/mongo.rb', line 33

def geo_near(center, opts = {})
  opts = self.options.merge(opts)
  # convert point
  center = center.to_lng_lat if center.respond_to?(:to_lng_lat)

  # set default opts
  opts[:skip] ||= 0

  if unit = Mongoid::Spacial.earth_radius[opts[:unit]]
    opts[:unit] = (opts[:spherical]) ? unit : unit * Mongoid::Spacial::RAD_PER_DEG
  end

  if unit = Mongoid::Spacial.earth_radius[opts[:distance_multiplier]]
    opts[:distance_multiplier] = (opts[:spherical]) ? unit : unit * Mongoid::Spacial::RAD_PER_DEG
  end

  opts[:distance_multiplier] = opts[:unit] if opts[:unit].kind_of?(Numeric)

  # setup paging.
  if opts.has_key?(:page)
    opts[:page] ||= 1
    opts[:paginator] ||= Mongoid::Spacial.paginator()

     if opts[:per_page].blank?
       opts[:per_page] = case opts[:paginator]
                        when :will_paginate
                          @document.per_page
                        when :kaminari
                          Kaminari.config.default_per_page
                        else
                          Mongoid::Spacial.default_per_page
                        end
       opts[:per_page] = opts[:per_page].to_i
     end

  end
  opts[:query] = create_geo_near_query(center,opts)
  results = klass.db.command(opts[:query])
  Mongoid::Spacial::GeoNearResults.new(klass,results,opts)
end