Search code examples
ruby-on-railsgoogle-mapsruby-on-rails-4gmaps4railsgmaps4rails2

gmaps4rails v2 polygon click event


What I am trying to do is something similar to this (how to set a zoom level using Gmap4rails)
but instead of:

google.maps.event.addListenerOnce(Gmaps.map.getMapObject(), 'idle', function(){}

I want something like

google.maps.event.addListenerOnce(polygon, 'click', function(){}  

_
So I tried to do this as an experiment:

handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
      polygon = handler.addPolygons(<%= raw @myhash.to_json %>);
}
google.maps.event.addListener(polygon, "click", function( evt ) {
      alert("hello!");
});

But it doesn't work....

So my question is, how would I add a listener for Polygons?


Solution

  • It's a matter of variable scope and the real google object lives within the gmaps4rails proxy object:

    handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
      var polygons = handler.addPolygons(<%= raw @myhash.to_json %>);
    
      for (var i=0;i < polygons.length; i++){
        var polygon = polygons[i];
        google.maps.event.addListener(polygon.getServiceObject(), "click", function(evt) {
          alert("hello!");
        });
      }
    }