1

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!!

1

2 Answers 2

2

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.

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

3 Comments

Oh that makes sense! I knew I was missing something. And you're right, I should declare my variables outside the loop, my bad. Thanks! :D
Sorry, one more question then I'll leave you alone. If I were to do the same with the info window, in that it would return the info from titleNode.nodeValue, how can I make a function to return that?
You wouldn't have to do anything - objects like that don't form closures like that, the way an inner function does. You should be fine
2

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);
    });
}

1 Comment

@JessicaStanley: You're welcome. Same concept... variables are scoped only within functions, not blocks. I just prefer named functions for code clarity. Inline immediately invoked function expressions look ugly to me.

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.