Closure issue with Listener and Google Maps markers

dom-events, google-maps, javascript, listener

Solution

Try this:

for (var i = 0; i < markers.length; ++i) {
  // ... like what you have already ...
  (function(permalink) {
    google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
  })(permalink);
}

By making a new lexical scope with a copy of the "permalink" value at each iteration, your handlers should work better.

Problem

I want to add a Listener event to each generated marker, so that when you click a marker you are redirected to the permalink url. With the code below the permalink value is the same for every marker(it get's the last value). I've read about closure problems and that seems to be what I'm having. I don't really get the examples I've looked at though. Can somebody take a look at my code and point me in the right direction? Any help is greatly appreciated! ``` downloadUrl("http://localhost/map/generatexml.php", function(data) { var xml = parseXml(data); var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { var permalink = markers[i].getAttribute("permalink"); var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))); var marker = new google.maps.Marker({map: map,position: point,icon: icon.icon,shadow: icon.shadow,title: name}); google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;}); } ```

Original source