Search code examples
ruby-on-railsrubygmaps4rails

gmaps4rails get latitude and longitude in the server


I'm reading about 'gmaps4rails', but I have a question about the gem. Is possible obtain the location (lat, lng) only with the address?


Solution

  • Yes it is, but I would first use the Geocoder gem.

    gem 'geocoder'
    

    You need to create a migration to add latitude and longitude floats to your table

    rails g migration AddLatitudeAndLongitueToModel latitude:float longitude:float
    

    Obviously, replace Model with your table name. then run rake db:migrate

    Then in your model, make sure the attribute for an address is being geocoded

    geocoded_by :location # replace location with the attribute of the address
    

    I would also add this:

    after_validation :geocode, if: ->(model_name){ model_name.location.present? and model_name.location_changed? }
    

    to avoid unnecessary API requests. Once again, change model_name with your model and location with the attribute that has the address.

    When you you create a new post now, it will have longitude and latitude coordinates that you can use with Gmap4rails

    So you can now you Gmap4rails like this:

    hash = Gmaps4rails.build_markers(@post) do |post, marker|
      marker.lat post.latitude
      marker.lng post.longitude
    end
    

    Here is the GitHub docs for the Geocoder gem. Has pretty much everything you need to know to add this to your app.

    Hope this can get you started in the right direction.