Integrating Google Maps in Your Rails 2.0 App.

NOTE:  THIS IS AN OLD POST AND THE INSTRUCTIONS MAY BE OUTDATED. YMMV

In my first real post in a year, I thought I’d share some Ruby stuff I’ve recently done – Integrating your Rails 2.0 app with Google Maps.

So, here is what we are aiming to accomplish: You are going to provide an address, say 123 Foobar St, Anywhere, MN 55812. We are going to send it to a geocoder, get the longitude and latitude, send that to Google, and get back the map information.

whew. Actually, its not nearly as hard as it sounds.

First, install the google-geocode gem:

sudo gem install google-geocode

The install the ym4r_gm, which will talk to Google for us.

script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm

Alright, finally, include the google-geocode gem in your controller.

require 'rubygems'
require 'google_geocode'

Now, you will need to get an API key from Google, and then put that key in the newely created config/gmaps_api_key.yml (as Drew Bushaw points out) or hard code it (Which I do in the example). There should be three keys already in there, and they will work when using your local machine, but will not with anything other than localhost. Alternativly, if you want to hardcode it in, place it where I have “your api key here” in the next section.

Add to your page header (prolly your layout and view) to include the required API javascripts, etc…
<%= GMap.header %>
<%= @map.to_html %>

Ok, now heres the fun. To get the geocode information, simply:

gg = GoogleGeocode.new "your api key here" #hard coded
#not hardcoded
#gg = GoogleGeocode.new YAML.load_file(RAILS_ROOT +‘/config/gmaps_api_key.yml’)[ENV['RAILS_ENV']]

loc = gg.locate @property.full_address
Now, I have @property and full_address is its full address (123 Foobar, Somecity, MN 55812 for example). You can also try it without some vitals, such as zip code.

Now we have to send Google Maps the correct information:

@map = GMap.new("map_div")
@map.control_init(:small => true) #add :large_map => true to get zoom controls
@map.center_zoom_init([loc.latitude, loc.longitude],14)
@map.overlay_init(GMarker.new([loc.latitude, loc.longitude],:title => @property.name, :info_bubble => loc.address))

Notice, “map_div”, which will come into play in the next step. Some useful tid bits here include the :title, which will be the title of the pin on the map, :info_bubble which will appear when you hover over the pin, and where I specified “14″. Here you specify the altitude the map will be at. Experiment for whatever your needs are.

Now, the final thing you need to do is put this to work in your view.

<%= @map.div(:width => 493, :height => 300) %>

As you can see, I’ve specified a :width and :height. Now, fire everything up and you should get something similar to…

screen_grab_google_maps_1_5_07

Now in my case I had people inputing address and if/when they enter one that is non-existent or incorrect, I had to catch it since a google-geocode will throw a big error if you give it bad information.

Enjoy!

Tags: , , ,

31 Responses to “Integrating Google Maps in Your Rails 2.0 App.”

  1. [...] Integrating Google Maps in your Rails 2.0 application [...]

  2. Dewey Bushaw says:

    A couple of things I noted while following your directions:

    To use the GM API Key you specified in config/gmaps_api_key.yml:

    Use:
    gg = GoogleGeocode.new YAML.load_file(RAILS_ROOT + ‘/config/gmaps_api_key.yml’)[ENV['RAILS_ENV']]

    Instead of:
    gg = GoogleGeocode.new “your api key here”

    info_bubble did not work for me so I changed it to info_window:
    Use: :info_window => loc.address
    Instead of: :info_bubble => loc.address

    Just to round out the tutorial for those who have not used YM4R_GM (like me):

    When putting the map div into your view also make sure to put this in the (if you use a layout then put it there):

  3. Dewey Bushaw says:

    This got cut-off I believe.

    When putting the map div into your view also make sure to put this in the (if you use a layout then put it there):

    Awesome tutorial man. I truly appreciate your help on this!

  4. John says:

    Thanks for the additions Dewey!

  5. peter says:

    I followed your instruction, but the browser an empty page.

    I had to add

    in the header, and I finally at least could see the google he google logo and controls.
    However it doesn’t show the map.

    When I change the zoom with the slide control I can see, that google tries to fetch the map data from the server.
    But no Map is displayed.

  6. John says:

    Hey Peter,
    Sounds like the Goecoding plugin isn’t getting the address info like it wants.

    You might want to make sure that loc.latitude and loc.longitude are getting correct values.

    Good luck!

  7. Snehal says:

    I tried to integrate google map as per the tutorial, somehow its not working.There is no error but the map is not visible in the view (html page of the application). The space for the map (specified width and height) is left blank.

    Is there anything else to be done to see the map on the page?

  8. Ch.SrinivasReddy says:

    The Google Maps key is the primary configuration setting you need to get started. There are some others you will need for later chapters, however. You can add these to config/environments/development.rb file as well:

    TIGERLINE_DIR=”/path/to/your/tigerline/data”
    YAHOO_API_KEY=”your_yahoo_api_key”
    UK_POSTCODE_DIR=”/path/to/your/uk/postcode/data” #the directory, not the file

  9. tim says:

    I had some problems as well. First, gmaps_api_key.yml was not created in RAILS_ROOT/config/ so I manually moved in gmaps_api_key.yml.sample. Then I get the same blank screen. This blog is really frustrating, as it leaves out the source code in the comments.

  10. John says:

    Thanks everyeone. I’ve updated the post to include Dewey’s suggestion and corrected my mistake:

    I suggested putting your api key in the gmaps_api_key.yml file located in /config, but my example code showed the api key hardcoded. In my project I had it hard coded and it worked beautifully for me. I’ve added Dewey’s code in the example, both should work for you.

    Also, code can be inserted in a comment, but it must be wrapped in <code></code> tags.
    <code></code>

  11. Matt says:

    whoops, that last post got screwed, here it is again

    Great tutorial! But I noticed a mistake, instead of
    , it should be

  12. John says:

    @Matt
    I think your code got parsed out. The post right above yours explains how to get code to look right.

  13. Lukar says:

    I cannot install ym4r_gm plugin…

    i am using

    script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm

    the plugin is not generated under the vendor folder and i dont see the google key file in the appropiate folder

    ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]

  14. Thyagarajan Shanmugham says:

    Hi Lukar
    Try installing the gem.. in linux we do it like $ sudo gem install ym4r , i dunno how you do it in window!

  15. Jerry says:

    So, by changing to , I was able to get this to work.

  16. [...] Adding Google Map to Rails 2 September 1, 2008 — seaquid Here is what I did to add Google Map to my website. I follow the following tutorial. [...]

  17. I can’t get the require ‘google_geocode’ to work it claims that “no such file to load — google_geocode” Ideas on this?

  18. John says:

    @Richard

    Make sure you ‘require rubygems’ also.

  19. @John

    I finally got it working, just can’t get it to read api key from the yml file. Is there a better way to do this some type of variable? also how are you handling none findable addresses?

  20. John says:

    @Richard
    For a nonfindable address, I believe @map will be nil, so you could do something like:

    < % unless @map.blank? %>
    .. code here
    < % end %>
    

    As for the yaml file not being read correctly, is the gmaps_api_key.yml being created on plugin installation? If not, I’d look at the plugin code (/vendor/plugins/…) and look for an obviously named variable.

    Honestly, I haven’t used any of this for about a year now, so I’m going off memory.. :)

  21. Shawn says:

    I am unable to install the plugin. is there a problem?

  22. The.Ewok says:

    In Rails 2.2.2 if you had the problem
    undefined method ‘relative_url_root’ for ActionContoller::AbstractRequest:Class

    Find the line (it was like 35 in mine)

    a < \n” unless option[:without_js]

    And replace the “AbstractRequest” with “Base”
    Should work fine then

  23. I can’t get it to load my api key when doing the following

    gg = GoogleGeocode.new “mykey”

    When i look at the source for the page the key is missing. Ideas?

  24. noobie says:

    Thanks for this great tutorial

  25. Ritesh says:

    Hi John Yerhot,

    I am getting problem to find locations, for city name it is working fine

    e. g.

    city_name = “jaipur”

    loc = gg.locate(city_name) ## working fine

    full_address = “S-5, Jyoti Nagar Extension, bais godam, near new vidhan sabha., Ph No. 0141-2740080, jaipur, rajasthan”

    loc = gg.locate(full_address) ### not working

  26. QAS says:

    This does not seem to work for me, do you by any chance have a sample source code available that i can play with?

  27. FM says:

    Need help with something very basic. Done will all the pre-reqs except for setting up the view. I have added
    GMap.header
    @map.to_html
    in the layout header ( in my cases it is addresses.html.erb).
    I am getting nil.to_map. In my actioncontroller, the loc latitude / long is showing up fine. I have not been able to finish if off, the only piece is the view. Would really appreciate some help.

  28. FM says:

    Got most of it working. Need some help with the view. I have put in my layout for addresses.html.erb. I getting a nil.to_html in my address show view. I have not got to 493, :height => 300) %>. Would appreciate some help.

  29. faisal says:

    Hi,
    i am facing problem while using “ym4r_gm” plugin i am finding error in this line . Error is undefined method `relative_url_root’ for ActionController::Base:Class
    have any one faced this error? Kindly tell me the solution if any one has

  30. Ravinder says:

    I am getting following error which could entirely be related to xml parsing. Any help would be appreciated

    undefined method `elements’ for #

    And the error is coming from following line
    loc = gg.locate “1234 some street, some city, state zip”

Leave a Reply