apneadiving / Google-Maps-for-Rails

Enables easy Google map + overlays creation in Ruby apps
https://apneadiving.github.io/
MIT License
2.27k stars 382 forks source link

Attach custom data to markers #478

Closed fabn closed 9 years ago

fabn commented 9 years ago

I'm using the MarkersBuilder ruby helper to build some marker data and it's awesome, however I have an issue. In the rubydoc you attach custom data to the marker with this syntax:

markers = Gmaps4rails.build_markers(collection) do |(code, state), marker|
  marker.lat state['latitude']
  marker.lng state['longitude']
  marker.title state['name']
  marker.json state: code, id: state.id # here are my custom data
end

What's that for? I'm adding markers to map using the handler:

  addMarkers: (data)=>
    @deleteMarkers()
    @markers = @handler.addMarkers(data)
    # Here I'm attaching a custom click handler
    google.maps.event.addListener(m.getServiceObject(), 'click', @myClickHandler) for m in @markers

  myClickHandler: (evt) ->
    # How to get state code from the clicked marker???

  # Later
  $.getJSON(myUrl).done(@addMarkers)

In myClickHandler I don't know how to access the code and the id I stored in the ruby code for the clicked marker.

plicjo commented 9 years ago

Hey @fabn:

You can't use the .addMarkers method when you are building markers with custom data.

You have to build them by map.

You can check it out in the wiki here: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Adding-an-id-to-markers-and-access-them-later

fabn commented 9 years ago

Yes, I found out that. I've added this code to handle the situation:

# Monkey patch after init to attach custom json to marker
Gmaps.Google.Builders.Marker.prototype.after_init = ->
  @serviceObject[k] = v for k,v of @args.data # Attacching data to already built marker

In this way I can attach custom data automatically with no restrictions

markers = Gmaps4rails.build_markers(collection) do |item, marker|
  marker.json data: {id: item.id, foo: item.foo} # marker (serviceObject) will have a id and a foo properties
end
plicjo commented 9 years ago

Wow, that's clean!

Can we close this @apneadiving?

apneadiving commented 9 years ago

@fabn nice way :) @plicjo here we go ;)