Okay, so I realize I’m the 100th person asking a question about this, but even after researching and trying different things for days now, I can’t figure it out.
I have a function that will create markers on a google map. I will pass this function the coordinates as well as the HTML that will be displayed in the infoWindow that should be attached to each marker.
The problem that so many other people have is that even in my super simple example the content of the infoWindow is always the last content set for any infoWindow instead of the content set when creating a specific marker.
How can I fix this?
Here’s my code:
var somerandomcounter = 0;
function addMarkerNew(){
markers[somerandomcounter] = new GMarker(new GLatLng(52.3666667+somerandomcounter,9.7166667+somerandomcounter),{title: somerandomcounter});
map.addOverlay(markers[somerandomcounter]);
var marker = markers[somerandomcounter];
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<b>"+somerandomcounter+"</b>");
});
somerandomcounter++;
}
The issue here is variable scope. Let’s break it down:
The easiest way to fix this is to pass the
somerandomcountervariable to one of the functions as an argument – this will keep the reference in the click handler pointing to the locally scoped variable. Here are two ways to do this:Pass the counter as an argument to
addMarkerNew:Make a new function to attach the click handler, and pass the counter into that function: