Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Google Maps API v3 integration in CoffeeScript, with non-JS Static Maps fallback
#= require jquery
#= require jquery_ujs
#= require lib/modernizr
#= require lib/jquery.lettering
#= require_tree .
$ ->
<section class="location">
<%= google_map_tag id: "wedding_map", address: "225 N Michigan Ave, Chicago, Illinois, 60601", zoom: 13, mark_center: true, width: 500 %>
$.fn.googleMap = () ->
element = $(this).get(0)
zoomLevel = $(this).data('zoom') || 8
if $(this).data('size')
[width, height] = $(this).data('size').split('x')
$(this).css({width: Number(width), height: Number(height), background: '#fff'})
wrapperElem = $(this).wrap('<div class="map-wrap"/>').css({background:'#fff'})
$(this).hide() # To avoid confusing Flash Of Non-interactive Map Content
geocoder = new google.maps.Geocoder
geocoderParams =
address: $(this).data('address') || "225 N Michigan Ave, Chicago, Illinois, 60601"
region: "US"
results = geocoder.geocode geocoderParams, (results, status) ->
if status == google.maps.GeocoderStatus.OK
latlng = results[0].geometry.location
mapOptions =
mapTypeControl: false
overviewMapControl: false
zoom: zoomLevel
center: latlng
mapTypeId: google.maps.MapTypeId.ROADMAP
map = new google.maps.Map(element, mapOptions)
marker = new google.maps.Marker
position: latlng
map: map
$(element).show() # Time to re-show the element
module MapsHelper
def google_map_tag(options={})
options.reverse_merge!(width: 600, height: 300, mark_center: true, zoom: 10)
static_map_tag = image_tag(static_map_url(options), width: options[:width], height: options[:height], alt: "Map for #{options[:address]}")
content_tag(:div, static_map_tag, id: options[:id],
data: {
googlemap: true,
size: "#{options[:width]}x#{options[:height]}",
address: options[:address],
marker: true,
zoom: options[:zoom]
def static_map_url(options)
map_params = [].tap do |p|
p << ["size", "#{options[:width]}x#{options[:height]}"]
p << ["zoom", options[:zoom]]
p << ["center", options[:address]]
p << ["markers", options[:address]] if options[:mark_center]
p << ["maptype", "roadmap"]
p << ["sensor", "false"]
"" + { |p| k,v=*p; "#{k}=#{CGI.escape(v.to_s)}" }.join("&")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment