Skip to content

Google maps in rails-3

April 15, 2011

Using a gmaps4rails gem to display a map in our application

create a rails application

$ rails new gmaps -d mysql

then configure mysql  password

In Gemfile add a gem as ==== gem ‘gmaps4rails’

and bundle it

create a scaffold  $ rails g scaffold Location name:string address:string longitude:float latitude:float.

remove the longitude and latitude fields in _form.html.erb

After that, add this in layout

<%= yield :head %> (in your header) <%= yield :scripts %> (in your footer)


  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
  <%= yield :head %>
<%= yield %>
<%= yield :scripts %>

In model /app/models/location.rb to add

class Location < ActiveRecord::Base
      def gmaps4rails_address
       def gmaps4rails_infowindow
         "<h4>#{name}</h4>" << "<h4>#{address}</h4>"

add the line in controller /app/controllers/locations_controller.rb

def index
    @locations = Location.all
    @json = Location.all.to_gmaps4rails

In your view app/views/locations/index.html.erb to add a last line as

    <%= gmaps4rails(@json) %>

then start the server to put the name and address, longitude and latitude as set automatically,
then will be show the markers as corresponding address and click the marker icon
it will shows infowindow as name and address

Sample in heroku:

3 Comments leave one →
  1. Marat Galiev permalink
    May 23, 2011 9:33 am

    Hi! Thanks for great post, but I had a error while I’m trying to create new location via scaffold,
    error was:
    undefined method `gmaps’ for #
    Rails.root: /var/www/brandbk

    Application Trace | Framework Trace | Full Trace
    app/controllers/locations_controller.rb:46:in `block in create’
    app/controllers/locations_controller.rb:45:in `create’


    “commit”=>”Create Location”}

    Like this:

    Can you help me please?

  2. schamane permalink
    January 11, 2013 1:44 am

    I found solution
    for this
    undefined method `gmaps’ for #

    Add to your database column `gmaps` boolean type.
    And all will be works!

  3. anees permalink
    August 2, 2013 11:40 pm

    I get an error in js saying gmaps is not defined causing the map not to display in heroku

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: