Skip to content
cutalion edited this page Mar 21, 2013 · 2 revisions

Here is a snippet from @jmcopeland, gmaps4rails is just an include away:

     class Venue
      include Gmaps4rails::ActsAsGmappable
      include Mongoid::Document
      include Mongoid::Geo

      field :location, :type => Array, :geo => true, :lat => :latitude, :lng => :longitude

      geo_index :location
      #...
    end

In the very near future there will be support for Mongoid::Geospatial, the successor of Mongoid::Geo - something like this (this example also includes geocoder integration):

     class Venue
      include Gmaps4rails::ActsAsGmappable
      include Mongoid::Document
      include Mongoid::Geospatial
      include Geocoder::Model::Mongoid
    
      after_create :perform_geocoding # attempt if enough address items are available

      # rake db:mongoid:create_indexes
      field :location,  type: Point,    spatial: {lat: :latitude, lng: :longitude, return_array: true }

      acts_as_gmappable :lat_lng_array => :location

      field :location, :type => Array, :geo => true, :lat => :latitude, :lng => :longitude

      # use geocoder indexing?
      geocoded_by :address_str, coordinates: :location, :skip_index => true
   
      embeds_one :address,  :as => :addressable

      delegate  :number, :street, :city, 
                :zip_code,  :region, :country,   
                :to => :address

      Address.location_fields.each do |field|
        meth_name = "#{field}="
        define_method meth_name do |value|
          self.address = Address.new unless self.address
          address.send(meth_name, value)
          perform_geocoding if respond_to? :perform_geocoding # perform geocode on any address change?
        end
      end

      def latitude
        perform_geocoding unless location
        location[0] if location
      end

      def longitude
        perform_geocoding unless location
        location[1] if location
      end

      def address_str
        "#{address.street}, #{address.city}, #{address.country}" 
      end  

      def perform_geocoding
        geocode if !location && address_geolocatable?
      end

      def address_geolocatable?
         address && !address.street.blank?
      end
    end