hsym
hsym

Reputation: 5417

gmaps4rails: How to retrieve json value from the controller?

I've got a shop model. I would like to output a simple alert box that displays a shop name using javascript when I click on a marker of a shop on the map.

This is my code:

# controller
@json = Shop.all.to_gmaps4rails do |shop, marker|
  marker.json({ id: shop.id, name: shop.name })
end

# view
<%= gmaps("map_options" => { auto_zoom: false, zoom: 2, class: "homepage-map" },
      "markers" => { data: @json,
                     options: { do_clustering: true,
                                clusterer_maxZoom: 11,
                                raw: "{ animation: google.maps.Animation.DROP }" }
                    })
%>

<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
Gmaps.map.callback = function() {
  for (var i = 0; i <  this.markers.length; ++i) {
    google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', function() {
      alert(put something here);
    });
  }
};
</script>
<% end %>

This is my first time dealing with json so I've read some introductory articles on json and also json in javascript. I was wondering how this is done with gmaps4rails.

Upvotes: 0

Views: 334

Answers (1)

apneadiving
apneadiving

Reputation: 115521

This should do the trick:

<script type="text/javascript" charset="utf-8">
function handleMarkerClickClosure(marker) {
  return function() {
    alert(marker.name);
  }
}

Gmaps.map.callback = function() {
  for (var i = 0; i <  this.markers.length; ++i) {
    google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', handleMarkerClickClosure(Gmaps.map.markers[i]) );
  }
};
</script>

Upvotes: 1

Related Questions