Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 224c0ce48d
Fetching contributors…

Cannot retrieve contributors at this time

file 65 lines (55 sloc) 1.687 kb
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
module Sequel
  module Plugins
    module Mappable

      def self.apply(model, opts={}, &block)
        model.send(:include, Geokit::Geocoders)
        model.send(:include, Geokit::Mappable)
      end

      def self.configure(model, opts={}, &block)
      end

      module ClassMethods
        def acts_as_mappable
          true
        end

        def distance_column_name
          :distance
        end

        def lat_column_name
          :lat
        end

        def lng_column_name
          :lng
        end

        def distance_sql(origin)
          lat = deg2rad(origin.lat)
          lng = deg2rad(origin.lng)
          multiplier = units_sphere_multiplier(:kms)
          %|
(ACOS(least(1,COS(#{lat})*COS(#{lng})*COS(RADIANS(lat))*COS(RADIANS(lng))+
COS(#{lat})*SIN(#{lng})*COS(RADIANS(lat))*SIN(RADIANS(lng))+
SIN(#{lat})*SIN(RADIANS(lat))))*#{multiplier})
|
        end
      end

      module InstanceMethods
      end

      module DatasetMethods
        def bounded_location(origin, within)
          bounds = Geokit::Bounds.from_point_and_radius(origin, within, :units => :kms)
          sw, ne = bounds.sw, bounds.ne
          filter = self
          if bounds.crosses_meridian?
            filter = filter.filter{(lng < ne.lng) | (lng > sw.lng)}
          else
            filter = filter.filter{(lng < ne.lng) & (lng > sw.lng)}
          end
          filter.filter{(lat < ne.lat) & (lat > sw.lat)}
        end

        def area(origin, within)
          sql = model.distance_sql(origin)
          bounded_location(origin, within).filter{sql.lit <= within}
        end
      end
    end
  end
end
Something went wrong with that request. Please try again.