[thelist] Googlemap script

Lee Kowalkowski lee.kowalkowski at googlemail.com
Thu Mar 29 10:27:49 CDT 2012

On 29 March 2012 13:24, Chris Price <chris.price at choctaw.co.uk> wrote:

> I know the problem is that its picking up the last variable in a for next

loop but I can't figure out the solution.

Yeah, declaring the marker inside your loop is misleading, because it will
still be a function-scoped variable.  I mean, there is 1 marker variable,
and when your loop is over, it is assigned to the last marker in your

So when you do this:

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

marker is a closure over that function-scoped variable.

The quickest/easiest solution to this is to create another function to
obtain a separate closure for each marker:

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

and call addMarkerClickEventHandler(infowindow, map, marker) inside your

There are possibly more elegant ways to solve it, e.g. by making your event
handler reference 'this' instead of 'marker', but that depends on the
execution context in which the event handler is going to be called (I don't
know if there's anything special about the google maps API that would
prevent this from working as expected).  And then there's also assigning
the click event handler to a parent element instead of each individual
marker, and relying on event bubbling, then inspecting the event to figure
out which marker had been clicked.  More elegant, but also more involved!


More information about the thelist mailing list