为什么我的谷歌地图事件监听器无法正常工作? [英] why are my google maps event listeners not working properly?

查看:227
本文介绍了为什么我的谷歌地图事件监听器无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将鼠标放在每个标记的侦听器上(有30个标记)并显示这些标记的infowindows。我为每个标记创建了监听器,但是当我将鼠标放在某个标记上时,它总是显示最后一个标记的infowindows。总结起来,我不能听其他标记。任何帮助,将不胜感激。在此先感谢我的代码:

I'm trying to handle mouse over listener for each marker(there are 30 markers) and to show infowindows for these markers. I created listeners for each markers but when my mouse over the some marker it shows always the last marker's infowindows. To sum up I can't listen other markers. any help would be appreciated. thanks in advance and here my code :

var listeners = [];
for(var i = 0; i < markers.length; i++){
  var marker = markers[i];
  var contentString = contents[i];
  listeners[i] = new google.maps.event.addListener(marker, 'mouseover', function() {
    var hideInfoWindows = function(){
        for (var j = 0; j < util.Common.infowindows.length; j++) {
          util.Common.infowindows[j].close(); 
        }
    }
    var addInfoWindow = function(){
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        //hideInfoWindows();
        util.Common.infowindows.push(infowindow);
        infowindow.open(util.Common.googlemap,marker);
    }
    addInfoWindow();
  });
}

我也使用 js集群库,但我认为这个问题与它没有关系。

I'm also using js cluster library but I don't think the problem is related with it.

推荐答案

我认为你的问题可能是你没有在循环中使用闭包,当事件侦听器被触发时,标记 contentString 变量指向最后一个标记。

I think your problem might be that you are not using a closure inside the cycle, and when the event listener is fired, the marker and the contentString variables are pointing to the last marker.

尝试像这样重写循环: p>

Try to rewrite the cycle like this:

var listeners = [];
for(var i = 0; i < markers.length; i++){
    (function(index){ //create a closure, variable 'index' will take its value from variable i, but won't be affected by changed i in the outer scope
        var marker = markers[index]; //use this scope's index variable instead of i
        var contentString = contents[index]; //use this scope's index variable instead of i
        listeners[index] = new google.maps.event.addListener(marker, 'mouseover', function() {
            var hideInfoWindows = function(){
                for (var j = 0; j < util.Common.infowindows.length; j++) {
                    util.Common.infowindows[j].close();
                }
            };
            var addInfoWindow = function(){
                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
                //hideInfoWindows();
                util.Common.infowindows.push(infowindow);
                infowindow.open(util.Common.googlemap,marker);
            };
            addInfoWindow();
        });
    })(i);
}

这篇关于为什么我的谷歌地图事件监听器无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆