Display a Google Map with Rails

Posted: October 18th, 2009 | Author: Pierre Olivier Martel | Filed under: General | Comments

In my last article on geopositioning with Rails and Google maps, we saw how to use the YM4R/GM plugin to find and store the longitude/latitude of an address using the Google Maps api. With these informations, we can now display the map to the user. We’ll see how to do this in three easy steps.

1. Prepare the map in your model

In your Geolocation model, start by adding this snippet of code which will initialize your map.

def map
  @map ||= prepare_map
end

def mapped?
  latitude && longitude
end

def coordinates
  [latitude, longitude]
end

private

def prepare_map
  return unless mapped?
  returning GMap.new("gmap") do |map| 
    map.control_init(:large_map => true, :map_type => true)
    map.center_zoom_init(coordinates, 15) # Set the center and zoo level
    map.overlay_init(GMarker.new(coordinates))
  end
end

The important method here is prepare_map. What it does is create a new map centered at the given coordinates. The overlay_init method sets a marker at the coordinates position. This is a basic vanilla map initialization. You might want to read the YM4R api for more options like adding an info window or multiple markers.

2. Call it from your controller

In our controller, we will set the @map variable to make it accessible in our view :

@map = customer.geolocation.map

3. Display the map in your view

You will need this snippet of code in the header section of your document to do the proper javascript imports and initializations :

= GMap.header
= @map.to_html

And in the body of your view, where you want to display the map, simply add :

@map.div(:width => 600, :height => 400)

This last line will generate a div with the id “gmap” (or whatever name you set in the GMap.new function). I find it’s cleaner to just set the width an height through CSS.

4. Adding complexity

This technique will only work if you display only one map on the page. The map needs to be visible on page load to be properly displayed. But what if there is multiple maps you want to display on the same page? And what if you want to show them in overlay popups? You probably don’t want to initialize them all on page load since it will freeze the client browser. This will require some javscript hacking. I will show you how to do that next week!