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

Panorama Theme by Themocracy