Google Maps in Ruby on Rails

By , August 6, 2009 11:49 pm

To generate google maps in ruby on rails is so easy and simple. I had recently generated a few maps in my projects by  YM4R/GM plugin.

Note: to support rails 3 application, certain changes are required in plugin. Those changes listed out here

There are few steps that you need to follow to generate simple gmap.

1. Install YM4R/GM plugin in your rails app.

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

2. Copy  the javascripts files from YM4R/GM plugin to public/javascript folder

3. Copy the gmaps_api_key.yml.example file to config folder and rename to gmaps_api_key.yml. Set the api key in that YML file.

If application is  in development mode then no necessary to change it.

4. Add below code in your controller.

def gmap

@map = GMap.new("map_div")

@map.control_init(:large_map => true,:map_type => true)

@map.center_zoom_init([22.792388,79.497070],4)

@map.overlay_init(GMarker.new([22.792388,79.497070],:title =>"India", :info_window =>"India"))

@map.record_init @map.add_overlay(GMarker.new([22.792388, 72.421875],:title =>"Ahmedabad", :info_window =>"Ahmedabad"))

end

#control_init : By  default false.

:large_map: true means you can get options of zoom in /zoom out of map on left side of map.

:map_type: true means you can change the type of map.

#center_zoom_init: Set the center point of map.

#overlay_init: Mark the position on map.

#record_init @map.add_overlay: Mark more position on map.

5. Add below code in your view.

<html><head><title>Test</title>
<%= GMap.header %>
<%= @map.to_html %>
</head><body>
<%= @map.div(:width => 600, :height => 400) %>
</body></html>

#You will get following output
Google Map

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

31 Responses to “Google Maps in Ruby on Rails”

  1. Rtdp says:

    Very information and easy to follow article for integrating maps in ruby on rails. I also your ‘Find latitude-longitude in rails’ article for integrating maps.
    Thanks
    I have a problem though, i want users to make markers on my maps. I haven’t found a solution for that through rails yet. Any suggestions ?

  2. Brijesh Shah says:

    you have to add below code in gmap definition.
    @map.event_init(@map, :click,
    “function(marker,point) { if (marker) {
    map.removeOverlay(marker);
    } else {
    map.addOverlay(new GMarker(point));
    }
    }”)
    Let me know if you find any other problem.

  3. suanqi says:

    i am not successful.there is error as bellow:

    消息: 缺少函数 (message:lack functions)
    行(row): 316
    字符(char): 27
    代码(code): 0
    URI: http://maps.gstatic.com/intl/zh-CN_ALL/mapfiles/178b/maps2.api/main.js

    消息: 对象不支持此属性或方法(message:object not support this property or method)
    行: 2
    字符: 1
    代码: 0
    URI: http://maps.gstatic.com/intl/zh-CN_ALL/mapfiles/176c/maps2.api/mod_jslinker.js

    消息: 缺少对象(lack object)
    行: 215
    字符: 26
    代码: 0
    URI: http://maps.gstatic.com/intl/zh-CN_ALL/mapfiles/178b/maps2.api/main.js

  4. Mamatha says:

    Thanks a lot for the instructions. I just wanted to embed a google map in an application. Perfect solution!

  5. SiNa says:

    Bonjour,

    Thank you for your code !! Sorry but we don’t speack very good english… :/
    My probleme : Your source doesn’t work for me..
    I have an error about GMap (“uninitialized constant ActionController::AbstractRequest”)… I am sad because in the first post from Ptdp, it is writting “easy to follow article for integrating maps in ruby on rails”…

    Thank you for your article !

  6. Brijesh Shah says:

    Sina,

    I think this rails version related issue with Google Map plugin.
    try out following link,might be it will help you.
    http://railsforum.com/viewtopic.php?id=24839

  7. SiNa says:

    Thanks you for your answer.
    Since the last post, our project runs :) (thanks your code)
    Our problem was the plugin Geokit…

    see you soon!

  8. Bernard says:

    Firstly sorry if I ask a newb question, new to ruby and programming. I am getting the following error while using your code.

    ActionView::TemplateError (undefined method `to_html’ for nil:NilClass) on line #6 of app/views/homes/index.html.erb:
    3:
    4:
    5:
    6:
    7:
    8: 600, :height => 400) %>
    9:

    app/views/homes/index.html.erb:6
    app/controllers/homes_controller.rb:7:in `index’

    What is wrong?

  9. Brijesh Shah says:

    Hi Bernard,

    ActionView::TemplateError (undefined method `to_html’ for nil:NilClass) ,this error shows that @map variable has not assign anything.

    Can you show me what you had implemented in controller part?

  10. Alok Anand says:

    can’t convert Ym4r::GmPlugin::Variable to String (Ym4r::GmPlugin::Variable#to_str gives Ym4r::GmPlugin::Variable)

    above is what I am getting as an error.
    And, when I am adding following code in mapping.rb file of plugin,

    def to_str
    @variable + “;”
    end

    I am getting the following output instead of the map

    var map; window.onload = addCodeToFunction(window.onload,function() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById(“map_div”)); map.setCenter(new GLatLng(22.792388,79.49707),4);map.addOverlay(addInfoWindowToMarker(new GMarker(new GLatLng(22.792388,79.49707),{title : “India”}),”India”,{})); map.addOverlay(addInfoWindowToMarker(new GMarker(new GLatLng(22.792388,72.421875),{title : “Ahmedabad”}),”Ahmedabad”,{}));map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); } });

    I think ‘to_html’ is having some problem.

    Any help is appreciated.

    Reagrds
    Alok Anand

    • Brijesh Shah says:

      Hi Alok,
      Which rails version are you using? This plugin is tested up to rails 2.3.2.

      Thanks
      Brijesh Shah

      • Alok says:

        Sir,

        I am using rails 3.0.3.
        Is there any new version of ym4r/gm or any other method for rails 3.0.3.

        Your help is surely required and welcome.

        Thanks
        Alok Anand

        • Brijesh Shah says:

          Hi Alok,

          Sorry for late reply. I was busy with some other stuff.

          Following things should be done to support rails 3.

          1. Add following method in class Varible under gm_plugin/mapping.rb

          def to_str
          @variable + “;”
          end

          2. user raw method for each google maps methods to avoid html contents.

          	<%= raw GMap.header %>
          	<%= raw  @map.to_html %>
          	<%= raw  @map.div(:width => 600, :height => 400) %>
          

          Let me know if you have any problems.

          Thanks
          Brijesh Shah

  11. Tapan says:

    I am using Rails3 and i did all the steps to integrate gmap as you have told but i got the errors as follow….

    v:* { behavior:url(#default#VML);} var map; window.onload = addCodeToFunction(window.onload,function() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById(“map_div”)); map.setCenter(new GLatLng(22.792388,79.49707),4);map.addOverlay(addInfoWindowToMarker(new GMarker(new GLatLng(22.792388,79.49707),{title : “India”}),”India”,{})); map.addOverlay(addInfoWindowToMarker(new GMarker(new GLatLng(22.792388,72.421875),{title : “Ahmedabad”}),”Ahmedabad”,{}));map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); } });

  12. Tapan says:

    it was helpful..

  13. Brijesh Shah says:

    Hi Alok,
    Are you still getting html output on page?
    Did you use raw method in code?

    <%= raw GMap.header %>
    <%= raw  @map.to_html %>
    <%= raw  @map.div(:width => 600, :height => 400) %>
    
  14. Alberto says:

    Hi,
    I’m trying to use it in Rails 3 and after modify mapping.rb and using raw method, the map is not displayed in my web, just a blank space.

    Any idea?

    thanks a lot!!

  15. Brijesh Shah says:

    Hi Alberto,

    What did you get page source? Also check is there any javascript error or not..

    Thanks
    Brijesh Shah

    • Brijesh Shah says:

      Hi
      This plugin also works in rails 3 after modify mapping.rb and using raw method.
      Did you add to_str method in Variable class? and let me know what did you get in page source (html contents)

      • Alberto says:

        Hi Brijesh and many thanks for your help:

        I modified the mappin.rb (before this i had an to_str error)
        and I’m using raw method.

        Now I obtain a routing error:

        DEPRECATION WARNING: ActionController::Base.relative_url_root is ineffective. Please stop using it. (called from header at ../vendor/plugins/ym4r_gm/lib/gm_plugin/map.rb:36)

        ActionController::RoutingError (No route matches “/eventos/DEPRECATION%20WARNING:%20ActionController::Base.relative_url_root%20is%20ineffective.%20Please%20stop%20using%20it.%20(called%20from%20header%20at%20/…/vendor/plugins/ym4r_gm/lib/gm_plugin/map.rb:36)/javascripts/ym4r-gm.js”)

        Any suggestion? I’m afraid the plugin isn’t still adapted to Rails 3 :S

  16. Alberto says:

    I solve it! changing the relative_url_root call in the map.rb for this line:

    a << "\n” unless options[:without_js]

    Now I can see the map!! (but I’m afraid will be more changes to do to adapt ym4r_gm to RoR 3..)

    I really appreciate your help, Brijesh. Thanks!!

  17. [...] already wrote a blog on how to use Google maps in rails.  Earlier blog is supported in rails 2.3.x [...]

  18. ray says:

    thanks for your example. but can you show me how to convert the string address enter by user , converting that address to a latitude/longitude ,and showing in the map?

  19. ray says:

    thanks, it works. your blog is really helpful.

  20. Dale-Kurt says:

    Hi Brijesh, I’m using rails 3.1.0 and I get the following error message

    vendor/plugins/ym4r_gm/lib/gm_plugin/key.rb:12:in `’: uninitialized constant Ym4r::GmPlugin::ApiKey::RAILS_ROOT (NameError)

Leave a Reply

*

Panorama Theme by Themocracy