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

2
  • You really should get in the habit of declaring variables with var Commented May 31, 2010 at 13:31
  • which one is not ? I did it outside the for loop in the complete file. Commented May 31, 2010 at 13:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

maybe using something like Prototype’s .bind() method would also work.
@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.
I know that, I doubt it would work without Closure (or rather the Closure to "prevent" the Closure).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.