1

I've got a page that retrieves a bunch of locations and some data about their associated markers and puts them on a Google Maps map. Each one is supposed to pop up its own little message when clicked on. However, clicking on ANY of them makes the most recently added message pop up at the most recently added marker. What gives? Am I not scripting the click event properly? Here's the relevant code:

var xmlDoc;
    if (window.XMLHttpRequest)
    {
    xmlDoc=new window.XMLHttpRequest();
    xmlDoc.open("GET","locs.php",false);
    xmlDoc.send("");
    xmlDoc=xmlDoc.responseXML;
    }
    // IE 5 and IE 6
    else if (ActiveXObject("Microsoft.XMLDOM"))
    {
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.load("locs.php");
    }

    var pins = xmlDoc.getElementsByTagName("pin");
    //alert(pins);

    for (i=0;i<pins.length;i++)
    {
       //alert(pins[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue);
       var point = new GLatLng( pins[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue, 
                                pins[i].getElementsByTagName("lon")[0].childNodes[0].nodeValue);
       var colord;
       var curgender = pins[i].getElementsByTagName("gender")[0].childNodes[0].nodeValue;
       if(curgender == "Male")
       {colord = blueOpt;}else if(curgender=="Female"){colord = pinkOpt;}else{colord = purpleOpt;}

       var marker = new GMarker(point, colord);
       var mess =  pins[i].getElementsByTagName("message")[0].childNodes[0].nodeValue;

       GEvent.addListener(marker, "click", function() {
         marker.openInfoWindowHtml(mess);
       });

       map.addOverlay(marker);

    }
  }
RedBlueThing
  • 42,006
  • 17
  • 96
  • 122
Jake
  • 600
  • 8
  • 20

2 Answers2

5

Daff is right about the scope. One alternative, however, is to use bindInfoWindowHtml() instead of a listener with openInfoWindowHtml(). Just replace the listener with this code:

marker.bindInfoWindowHtml(mess);


UPDATE: As a sidenote - because of closure, any variable created in a for loop will be remembered. A direct solution to the problem is to make a separate function to create the Listener.

Replace the listener with

createMarker(marker,mess);

and add the function:

function createMarker(marker, mess) {
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(mess);
    });
}
Chris B
  • 15,524
  • 5
  • 33
  • 40
  • 1
    Thank you, thank you, thank you. This is exactly what I needed but couldn't find. – Jake Jul 03 '09 at 18:54
0

I had this once, too. It is a scoping issue. I had to change my structure a little bit but maybe in your case changing the callback could already help:

GEvent.addListener(marker, "click", function() {
 marker.openInfoWindowHtml(pins[i].getElementsByTagName("message")[0].childNodes[0].nodeValue;);
});
Daff
  • 43,734
  • 9
  • 106
  • 120