Ruby on Rails Using GoogleMaps with Rails Auto-zoom a map using a coffee script class


Example

Provided an App.GoogleMap coffee script class with the google.maps.Map stored as @map and the google.maps.Markers stored as @markers, the map can be auto-zoomed, i.e. adjusted that all markers are visible, like this: on the map like this:

# app/assets/javascripts/google_maps.js.coffee
# ...
class App.GoogleMap
  # ...
  bounds: {}

  constructor: (map_div)->
    # ...
    @auto_zoom()

  auto_zoom: ->
    @init_bounds()
    # TODO: Maybe, adjust the zoom to have a maximum or 
    # minimum zoom level, here.

  init_bounds: ->
    @bounds = new google.maps.LatLngBounds()
    for marker in @markers
      @bounds.extend marker.position
    @map.fitBounds @bounds

To learn more about bounds, have a look at google's LatLngBounds documentation.