I just wrote a rails helper to assist me with adding google maps to my applications. It uses the layout/content_for template engine to insert javascript code into the header.
module ApplicationHelper
def js_for_google_maps( id = "map" )
content_for("header") do <<-JAVASCRIPT
<script src="http://maps.google.com/maps?file=api&v=2&key=#{GOOGLE_MAPS_KEY}" type="text/javascript"></script>
<script type="text/javascript">
Event.observe( window, 'load',
function() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("#{id}"));
var point = new GLatLng(37.763135, -122.4106);
map.setCenter(point, 15);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
);
Event.observe( window, 'unload', GUnload() );
</script>
JAVASCRIPT
end and return
end
end
The google maps key is defined in the environment files. Here is the one from development.rb corresponding to localhost:3000
GOOGLE_MAPS_KEY = "ABQIAAAASH81C6sj132EpSsZDgoERhTJQa0g3IQ9GZqIMmInSLzwtGDKaBQISjQeH9qFJ5o5SEiH-ulbhhxOPg"
Here is the template code that makes all this work:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>internaut design - agile software development - san francisco bay area</title>
<%= stylesheet_link_tag 'site' %>
<%= javascript_include_tag :defaults %>
<%= @content_for_header %>
</head>
Don’t forget to define your HTML
<div id="map"></div>
and CSS:
#map { width: 400px; height: 250px; }
1 Response to “rails helper for google maps”
Sorry, comments are closed for this article.

April 21st, 2007 at 04:57 PM
Sweet, though you missed half the fun of using @content_for@
And you rid yourself of the ugly instance variables :)