最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - adding marker listener in a loop in google maps api v3? - Stack Overflow

programmeradmin2浏览0评论

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 generated.

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.

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 generated.

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.

Share Improve this question asked May 30, 2011 at 22:34 Razor StormRazor Storm 12.3k20 gold badges95 silver badges151 bronze badges 1
  • Does alert(postID) in the event have the same issue? – Oliver Commented May 30, 2011 at 22:54
Add a ment  | 

1 Answer 1

Reset to default 7

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);
    });
})();
发布评论

评论列表(0)

  1. 暂无评论