GABRIELEROSELLI

Google Map View For Rails App

I recently built a view for a dynamic google map on a Rails application. Displaying the map then is as simple as dropping an iframe tag with parameters for latitude and longitude in the view. For this post I will be creating a personalized dynamic map for users.

When a user creates an account the app relies on the geokit-rails3 gem to geocode the user’s location and store the latitude and longitude in the database.

1 class User < ActiveRecord::Base
2  before_validation :geocode_address
3  
4  def geocode_address
5   geo = Geokit::Geocoders::MultiGeocoder.geocode(self.location)
6   errors.add(:address, "Could not Geocode address") if !geo.success
7   self.lat, self.lng, self.zip = geo.lat,geo.lng,geo.zip if geo.success
8  end
9 end

In the maps controller the index action is set to pass the params for latitude and longitude. Also the layout is set to false, so the application layout won’t show up in the iframe.

1 class MapsController < ApplicationController
2   layout false
3   def index
4     @lat = params[:lat]
5     @lng = params[:lng]
6   end
7 end

In order to really understand the code on the map index view reading the google maps JavaScript API docs it’s a must.

 1 <head>
 2  <style type="text/css">
 3   html { height: 100% }
 4   body { height: 100%; margin: 0px; padding: 0px }
 5   #map_canvas { height: 100% }
 6  </style>
 7  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
 8  <script type="text/javascript">
 9   var city = new google.maps.LatLng(<%= @lat -%>, <%= @lng -%> );
10   var place = new google.maps.LatLng(<%= @lat -%>, <%= @lng -%> );
11   var marker;
12   var map;
13   function initialize() {
14    var mapOptions = {
15     zoom: 15,
16     mapTypeId: google.maps.MapTypeId.ROADMAP,
17     center: city};
18     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
19     marker = new google.maps.Marker({
20     map:map,
21     draggable:true,
22     position: place
23    });}
24   }
25  </script>
26 </head>
27 <body onload="initialize()">
28   <div id="map_canvas"></div>
29 </body>

Once the map index view is ready, it can be placed in other views with the code below.

1 <iframe src="/map/?lat=<%= @user.lat %>&lng=<%= @user.lng %>&zoom=15" width="400" height="400" frameborder="0"></iframe>