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


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/
# ...
class App.GoogleMap
  # ...
  bounds: {}

  constructor: (map_div)->
    # ...

  auto_zoom: ->
    # 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.