2

I have some code here : http://bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js

That I use to draw some information about trucks direction.

The problem come from a function defined in a for loop like this one :

...

for(i = 0; i < nb_trucks; i++)
{
    ...

    contentString = '<div id="content">'+ trucks[i]['name'] + '</div>';

    current_window = new google.maps.InfoWindow({
        content: contentString
    });            

    infosWindow.push(current_window);

    current_marker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(trucks[i]['end']['lat'], trucks[i]['end']['lon']),
        draggable: false,
        title: trucks[i]['name']
    });
    markers.push(current_marker);

    google.maps.event.addListener(current_marker, 'click', function() {
        current_window.open(map, current_marker);
    });
}

In this code, you can see the last block

    google.maps.event.addListener(current_marker, 'click', function() {
        current_window.open(map, current_marker);
    });

And my problem is that current_marker in the addListener parameters is different from the one inside the function.

The current_window and the current_marker inside the function is overide at each loop turn.

How can I get it right ?

Thanks

Natim
  • 17,274
  • 23
  • 92
  • 150

1 Answers1

5

Wrap it in a closure (just this little section, no other changes) so you get the variable you want, like this:

(function(marker) { //a copy is passed, accessible as marker inside this function
  google.maps.event.addListener(marker, 'click', function() {
    current_window.open(map, marker);
  });
})(current_marker); //pass in the current value

This doesn't reference the same variable that's changing every loop, a copy of it is passed into the closure, so each time you run this it gets a copy of what current_marker is that that time passed in. If you're more curious about this, there are some great answers explaining closures in this question.

Community
  • 1
  • 1
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • maybe using something like Prototype’s .bind() method would also work. – Dormilich May 31 '10 at 13:17
  • @Dormilich: That is also just a closure, albeit wrapped in other code...but in this case core javascript does this very easily, no reason to include a library for anything like this. – Nick Craver May 31 '10 at 13:20
  • I know that, I doubt it would work without Closure (or rather the Closure to "prevent" the Closure). – Dormilich May 31 '10 at 15:49