Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing json json

Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing


This is a very common question in the google-maps tag and an easy mistake to make :).

What is happening is that your click event is being called asynchronously and it is picking up the current value in the marker variable in the getJSON callback (the last one in the list).

You need to wrap your addListener call in a function so that a closure is created around the marker variable that is being used in the click callback:

function listenMarker (marker){    // so marker is associated with the closure created for the listenMarker function call    google.maps.event.addListener(marker, 'click', function() {                        tooltip.open(map, marker);                    });}

Then call listenMarker from your main getJSON callback (where you are currently calling addListener).


YOu can also do this:

// so marker is associated with the closure created for the listenMarker function callgoogle.maps.event.addListener(marker, 'click', function() {                    tooltip.open(map, this);                });

Where "marker" is replace with "this" in the add listener call. Thus you can place the addListerner code at the same point you create the marker, and not have to create a new function.

http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/

Check out the full solution and a demo :D


Placing the addListener call into its own function also solves the problem of multiple infowindows all displaying the same text.