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!

This entry was posted in Google, Programming, Ruby On Rails and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

28 Comments

  1. Posted March 8, 2008 at 6:12 pm | Permalink

    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):

  2. Posted March 8, 2008 at 6:13 pm | Permalink

    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!

  3. Posted March 9, 2008 at 7:58 am | Permalink

    Thanks for the additions Dewey!

  4. Posted April 17, 2008 at 7:35 pm | Permalink

    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.

  5. Posted April 18, 2008 at 7:17 am | Permalink

    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!

  6. Snehal
    Posted May 15, 2008 at 12:52 am | Permalink

    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?

  7. Ch.SrinivasReddy
    Posted May 20, 2008 at 3:15 am | Permalink

    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

  8. tim
    Posted May 29, 2008 at 8:14 pm | Permalink

    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.

  9. Posted May 30, 2008 at 7:10 am | Permalink

    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>

  10. Matt
    Posted June 24, 2008 at 10:10 am | Permalink

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

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

  11. Posted June 24, 2008 at 6:14 pm | Permalink

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

  12. Lukar
    Posted July 27, 2008 at 11:41 am | Permalink

    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]

  13. Thyagarajan Shanmugham
    Posted August 26, 2008 at 10:29 am | Permalink

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

  14. Jerry
    Posted August 31, 2008 at 10:10 pm | Permalink

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

  15. Posted October 20, 2008 at 2:49 pm | Permalink

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

  16. Posted October 22, 2008 at 2:51 pm | Permalink

    @Richard

    Make sure you ‘require rubygems’ also.

  17. Posted October 23, 2008 at 5:24 am | Permalink

    @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?

  18. Posted October 28, 2008 at 8:00 am | Permalink

    @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.. :)

  19. Shawn
    Posted December 11, 2008 at 1:59 pm | Permalink

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

  20. The.Ewok
    Posted December 13, 2008 at 6:10 pm | Permalink

    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

  21. Posted December 17, 2008 at 8:12 am | Permalink

    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?

  22. noobie
    Posted March 12, 2009 at 6:20 pm | Permalink

    Thanks for this great tutorial

  23. Ritesh
    Posted May 26, 2009 at 1:35 am | Permalink

    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

  24. QAS
    Posted June 4, 2009 at 4:42 am | Permalink

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

  25. FM
    Posted June 9, 2009 at 7:22 pm | Permalink

    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.

  26. FM
    Posted June 9, 2009 at 7:27 pm | Permalink

    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.

  27. faisal
    Posted June 18, 2009 at 11:51 pm | Permalink

    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

  28. Ravinder
    Posted October 30, 2009 at 12:10 am | Permalink

    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”

3 Trackbacks

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

  2. By Adding Google Map to Rails 2 « TrAvid’s Weblog on August 31, 2008 at 11:18 pm

    [...] 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. [...]

  3. By Google maps on Ruby on Rails | Ruby On Rails on January 8, 2009 at 5:53 am

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>