NOTE: I\'m using v3 of the Google Maps API
I\'m trying to add an info window to each marker I put on the map. Currently I\'m doing this with the following code:
Hey everyone. I don't know if this is the optimal solution but I figured I'd post it here to hopefully help people out in the future. Please comment if you see anything that should be changed.
My for loops is now:
for (var i in tracks[racer_id].data.points) {
values = tracks[racer_id].data.points[i];
point = new google.maps.LatLng(values.lat, values.lng);
if (values.qst) {
tracks[racer_id].markers[i] = add_marker(racer_id, point, '<b>Speed:</b> ' + values.inst + ' knots<br /><b>Invalid:</b> <input type="button" value="Yes" /> <input type="button" value="No" />');
}
track_coordinates.push(point);
bd.extend(point);
}
And add_marker
is defined as:
var info_window = new google.maps.InfoWindow({content: ''});
function add_marker(racer_id, point, note) {
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
marker.note = note;
google.maps.event.addListener(marker, 'click', function() {
info_window.content = marker.note;
info_window.open(map, marker);
});
return marker;
}
You can use info_window.close() to turn off the info_window at any time. Hope this helps someone.
You are having a very common closure problem in the for in
loop:
Variables enclosed in a closure share the same single environment, so by the time the click
callback from the addListener
is called, the loop will have run its course and the info
variable will be left pointing to the last object, which happens to be the last InfoWindow
created.
In this case, one easy way to solve this problem would be to augment your Marker
object with the InfoWindow
:
var marker = new google.maps.Marker({map: map, position: point, clickable: true});
marker.info = new google.maps.InfoWindow({
content: '<b>Speed:</b> ' + values.inst + ' knots'
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:
Also keep in mind, that the v3 API allows multiple InfoWindow
s on the map. If you intend to have just one InfoWindow
visible at the time, you should instead use a single InfoWindow
object, and then open it and change its content whenever the marker is clicked (Source).
In My case (Using Javascript insidde Razor) This worked perfectly inside an Foreach loop
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, this);
});