Search code examples
javascriptruby-on-railsruby-on-rails-3gmaps4rails

Gmaps4rails : How to change appearance of marker when user clicks link in sidebar?


I'm trying to get this behavior with gmaps4rails : User clicks link in the sidebar, corresponding marker on the map changes image/color in order to make the selected one stand out from the others.

I've tried with this code

Gmaps.map.callback = function(){
        var len = Gmaps.map.markers.length;
        for(var i = 0; i < len; i++){
            marker = Gmaps.map.markers[i];
            google.maps.event.addListener(marker.serviceObject, 'click', (function(i){
                return function(){
                    console.log($(Gmaps.map.markers[i].serviceObject.ne.ga).attr("src", "/assets/marker_sprite2.png"));
                }
            })(i));
        }
    }

But this changes every marker's appearance, which is not very useful for what I'm trying to do !

Is there anyway to achieve this ?

EDIT : Made it work see answer below

EDIT 2 : While this solution worked for what I wanted, I stumbled upon an other issue with this method, see comment to answer below


Solution

  • You've a javascript issue. Actually, you can't make a closure with a changing counter: it will always be referenced with it's last value.

    Gmaps.map.callback = function(){
      for(var i = 0; i < Gmaps.map.markers.length; i++){
        marker = Gmaps.map.markers[i];
        google.maps.event.addListener(marker.serviceObject, 'click', 
          (function(marker){
            return function(){
             console.log($(marker.serviceObject.ne.ga).attr("src", "/assets/marker_sprite2.png"));
            }
          })(marker)
        )
      }
    }
    

    Your main issue is a bit long, not complex but long. The idea is the following:

    • add an id to each marker, you could use the block argument of the to_gmaps4rails method and add some more json

    • create the sidebar yourself and add the id to each line to know which marker you want when you click the li

    • loop all markers to get the one with the proper id

    • change it's picture