Inline function and global variable issue in Javascript

Posted by Natim on Stack Overflow See other posts from Stack Overflow or by Natim
Published on 2010-05-31T13:08:22Z Indexed on 2010/05/31 13:13 UTC
Read the original article Hit count: 251

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

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about global-variables