Ruby on Rails Using GoogleMaps with Rails Initialize the map markers using a coffee script class


Example

Provided an App.GoogleMap coffee script class and the marker information being stored in the data-address-fields attribute of the .google_map div, the map markers can be initialized on the map like this:

# app/assets/javascripts/google_maps.js.coffee
# ...
class App.GoogleMap
  # ...
  markers: []

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

  address_fields: ->
    @map_div.data('address-fields')

  init_markers: ->
    self = this  # to reference the instance as `self` when `this` is redefined.
    self.markers = []
    for address_field in self.address_fields()
      marker = new google.maps.Marker {
        map: self.map,
        position: {
          lng: address_field.longitude,
          lat: address_field.latitude
        },
        # # or, if `position` is defined in `ProfileFields::Address#as_json`:
        # position: address_field.position,
        title: address_field.value
      }
      self.markers.push marker

To learn more about marker options, have a look at google's MarkerOptions documentation and their guide to markers.