adding marker listener in a loop in google maps api v3?
I have a bunch of markers and wish to add a mouseover handler to each of them. I am looping through my coordinates, creating new markers and then adding a handler. In the handler I wish for it to modify the DOM element with a specific id.
The problem is, even though in the loop the id is changing through each iteration, the actual handler applied all use the last postId ge开发者_运维百科nerated.
for(i in results)
{
r=results[i][0];
var postId=results[i][1]; // Different for each i
if (status == google.maps.GeocoderStatus.OK)
{
markers.push(new google.maps.Marker({
map: map,
position: r[0].geometry.location
}));
console.log(postId);
google.maps.event.addListener(markers[markers.length-1], 'mouseover', function() {
console.log(postId);
});
}
}
The problem is that no matter which marker I hover over, postId is being printed out as "1".
However when I am going through the loop, the postId is different each time.
Console output:
21
20
12
10
9
3
2
1
However, when I hover over the markers it always says 1.
That's because you create one global postId
that all listeners share. You can create private versions like so:
(function () {
var postId=results[i][1];
google.maps.event.addListener(markers[markers.length-1], 'mouseover', function() {
console.log(postId);
});
})();
精彩评论