]> git.openstreetmap.org Git - rails.git/blob - app/models/concerns/geo_record.rb
Merge pull request #1151 from polarbearing/patch-1
[rails.git] / app / models / concerns / geo_record.rb
1 require "delegate"
2
3 module GeoRecord
4   extend ActiveSupport::Concern
5
6   # Ensure that when coordinates are printed that they are always in decimal degrees,
7   # and not e.g. 4.0e-05
8   # Unfortunately you can't extend Numeric classes directly (e.g. `Coord < Float`).
9   class Coord < DelegateClass(Float)
10     def initialize(obj)
11       super(obj)
12     end
13
14     def to_s
15       format("%.7f", self)
16     end
17   end
18
19   # This scaling factor is used to convert between the float lat/lon that is
20   # returned by the API, and the integer lat/lon equivalent that is stored in
21   # the database.
22   SCALE = 10000000
23
24   included do
25     scope :bbox, ->(bbox) { where(OSM.sql_for_area(bbox, "#{table_name}.")) }
26     before_save :update_tile
27   end
28
29   # Is this node within -90 >= latitude >= 90 and -180 >= longitude >= 180
30   # * returns true/false
31   def in_world?
32     return false if lat < -90 || lat > 90
33     return false if lon < -180 || lon > 180
34
35     true
36   end
37
38   def update_tile
39     self.tile = QuadTile.tile_for_point(lat, lon)
40   end
41
42   def lat=(l)
43     self.latitude = (l * SCALE).round
44   end
45
46   def lon=(l)
47     self.longitude = (l * SCALE).round
48   end
49
50   # Return WGS84 latitude
51   def lat
52     Coord.new(latitude.to_f / SCALE)
53   end
54
55   # Return WGS84 longitude
56   def lon
57     Coord.new(longitude.to_f / SCALE)
58   end
59 end