forked from mongoid/mongoid-geospatial
-
Notifications
You must be signed in to change notification settings - Fork 7
/
geospatial.rb
69 lines (56 loc) · 1.9 KB
/
geospatial.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
module Mongoid
module Geospatial
extend ActiveSupport::Concern
LNG_SYMBOLS = [:x, :lon, :long, :lng, :longitude]
LAT_SYMBOLS = [:y, :lat, :latitude]
EARTH_RADIUS_KM = 6371 # taken directly from mongodb
RAD_PER_DEG = Math::PI / 180
EARTH_RADIUS = {
:km => EARTH_RADIUS_KM,
:m => EARTH_RADIUS_KM * 1000,
:mi => EARTH_RADIUS_KM * 0.621371192, # taken directly from mongodb
:ft => EARTH_RADIUS_KM * 5280*0.621371192,
:sm => EARTH_RADIUS_KM * 0.53995680345572 # sea mile
}
mattr_accessor :lng_symbols
mattr_accessor :lat_symbols
mattr_accessor :earth_radius
mattr_accessor :factory
@@lng_symbols = LNG_SYMBOLS.dup
@@lat_symbols = LAT_SYMBOLS.dup
@@earth_radius = EARTH_RADIUS.dup
included do
# attr_accessor :geo
cattr_accessor :spatial_fields, :spatial_fields_indexed
self.spatial_fields = []
self.spatial_fields_indexed = []
end
def self.use_rgeo
require 'mongoid_geospatial/wrappers/rgeo'
end
def self.use_georuby
require 'mongoid_geospatial/wrappers/georuby'
end
module ClassMethods #:nodoc:
def geo_field name, options = {}
field name, {type: Mongoid::Geospatial::Point, spatial: true}.merge(options)
end
# create spatial index for given field
# @param [String,Symbol] name
# @param [Hash] options options for spatial_index
# http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand
def spatial_index name, options = {}
self.spatial_fields_indexed << name
index({name => '2d'}, options)
end
def spatial_scope field, opts = {}
self.singleton_class.class_eval do
# define_method(:close) do |args|
define_method(:nearby) do |args|
queryable.where(field.near_sphere => args)
end
end
end
end
end
end