Search code examples
rubyruby-on-rails-3google-maps-api-3mongoidgmaps4rails

How to geocode addresses by gmaps4rails and save coordinates in array?


I'm using gem mongoid_special instead of mongoid_geo. Main question is how to geocode with gmaps4rails entered places and save coordinates like lat and lng in right mongoid_special array fields? I predict many association for coordinates. Illustrative materials:

/haml view fields (autocompleted with google places)/
= f.text_field :from, :id => 'from'
= f.text_field :waypoints, :id => 'waypoints'
= f.text_field :to, :id => 'from'

class Trip
  include Gmaps4rails::ActsAsGmappable
  include Mongoid::Document
  include Mongoid::Spacial::Document

  field :from, :type => String
  field :waypoints, type => String
  field :to, type => String

  field :from_coordinate, type: Array, spacial: {lat: :latitude, lng: :longitude, return_array: true }
  field :to_coordinate, type: Array, spacial: {lat: :latitude, lng: :longitude, return_array: true }

  embeds_many :coordinates
end

class Coordinates
  include Mongoid::Document
  include Mongoid::Spacial::Document

  field :coordinates, type: Array, spacial: {lat: :latitude, lng: :longitude, return_array: true }

  embedded_in :trip
end

Further question is how to get reverse geocode from this fields and display data as google direction?

EDIT Thanks for hint my solution for from field below, with the rest I can manage somehow.

before_save :from

def from=(from)
   self.from_coordinate = Gmaps4rails.geocode(from).first
end

Solution

  • Here is what I suggest:

    • To get the data the way you want, create your own before_save filter and use the Gmaps4rails.geocode method described here.

    • To display direction, see here

    • no reverse geocoding is available in gmaps4rails