Setting variable name based on loop iteration

I hope I'm not overlooking an extremely easy solution when I ask this question.

I have a loop in a function in Javascript that gets the coordinates and name a location from an XML file, and creates markers on a custom made google map. I want these markers to be clickable and pop up an info window. I have the code written for it, and all the markers show up fine on the map. But when I click on any marker, only one info window appears on the first marker that was created. Here's what I did...

for(var i=0; i<items.length; i++) {
        var latitude = items[i].getElementsByTagName('Lat')[0].childNodes[0].nodeValue;
        var longitude = items[i].getElementsByTagName('Lon')[0].childNodes[0].nodeValue;
        var latlng = new google.maps.LatLng(latitude,longitude);
        var titleNode = items[i].getElementsByTagName('Name')[0].childNodes[0];
        var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                title: titleNode.nodeValue,
                icon: orangeCircle
        });

        var infoWindow = new google.maps.InfoWindow({
                content: 'Hello world'
        });

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

My guess (and it's really only a guess, I'm new to javascript) is that I need to create a new marker name for each marker. As in, each one shouldn't just be named "marker". I was thinking the easiest way to fix it was to create a variable name based on what iteration the loop was on, so marker1, marker2, marker3, etc. But I'm not sure how I could set the variable name to add a number to the end of it based on whatever iteration we're on.

Maybe I'm approaching this wrong. Is there any other way I could go about doing it if it's wrong? Thanks!!

Answers


You need to break the closure that your event handler has with map and marker.

google.maps.event.addListener(marker, 'click', (function(lmap, lmarker) { 
       return function() { infoWindow.open(lmap, lmarker); }
    })(map, marker)
);

The way you had it, the event handler was not creating a function that passed the values of map and marker to inforWindow.open, it was passing the actual variables themselves; it was creating a closure over those variables. Whatever those variables happened to end up as at the end of your function are what all of the handlers would use.

You break the closure by passing those variables to a function. Function parameters are passed by value, so this in effect creates a snapshot of those variables, and uses that value.

Also note that declaring these variables inside your loop does not help, since all variables have function scope in JavaScript. This means that even though you may have declared these variables inside a loop, the declarations are hoisted to the top of the function. It's the same as if you had actually declared those variables at the top of the function, which is why all variables in JavaScript should be declared at the very beginning of your function.


You can place all the logic in a function, pass it i, and it will just work.

for(var i=0; i<items.length; i++) {
    setUpMap( i );
}

Here's the function:

function setUpMap( i ) {
    var latitude = items[i].getElementsByTagName('Lat')[0].childNodes[0].nodeValue;
    var longitude = items[i].getElementsByTagName('Lon')[0].childNodes[0].nodeValue;
    var latlng = new google.maps.LatLng(latitude,longitude);
    var titleNode = items[i].getElementsByTagName('Name')[0].childNodes[0];
    var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: titleNode.nodeValue,
            icon: orangeCircle
    });

    var infoWindow = new google.maps.InfoWindow({
            content: 'Hello world'
    });

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

Need Your Help

Php: creating functions in a for () loop

php c

Does anybody know how I could write a function, that was able to create other functions, using the contents of a variable for it's name?

How to embed a clickable div inside another clickable div

javascript jquery html

In a previous question I asked about toggling a child div from the parent which was answered and the answer given works. Now I have a different issue: When I click anywhere within the inner (such ...

how can I change the legend for ggbiplot?

r pca ggbiplot

Actually I am trying to plot PCA by this package but when I plot the loading, I cannot change the legend as I wish (e.g. if I want to set the legend to (+)M it shows something else.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.