Search code examples
javascriptruby-on-railsgmaps4rails

getting id of marker on click


I'm using gmaps4rails to add a map to my rails app. I'm trying to log the age of a user by clicking on marker.

In my index action I have -

    @json = User.all.to_gmaps4rails do |user, marker|
      marker.json({ :id => user.id, :age => user.age })
    end

This is creating the map and adding all my markers.

If I put Gmaps.map.markers[0] in my js console I can see my object and can see it has an age property.

I'm trying to log that property through a click by doing something like this -

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

this.age is undefined. Obviously, it is logging the serviceObject rather than the marker object.

What am I doing wrong?


Solution

  • You're working with a closure and you're running into a problem where 'this' doesn't refer to the object that you think it does. In order to reference Gmaps.map.markers[*], first create an immediate function, pass in 'i' by value, and return a function that logs the .age property:

    <script type="text/javascript">
      Gmaps.map.callback = function() {
      for (var i = 0; i <  this.markers.length; ++i) {
        google.maps.event.addListener(
         marker.serviceObject, 'click', (function(i) {
            return function() {
                console.log(Gmaps.map.markers[i].age) 
            }
        })(i));
      }
     };        
    </script>
    

    Declaring functions (closures) in loops can be tricky. Here's a very helpful walk-through explanation I found: http://www.mennovanslooten.nl/blog/post/62