2012-03-28 78 views
0

我有以下代码,每次点击其中一个标记时,我会得到第一个infowindow。我有181个infowindows和181个标记。任何帮助赞赏。谷歌地图 - 不知道为什么我总是得到第一个infowindow

var i=0; 
$.each(in_locations,function(k,v){ 
    console.log(v); 
    var marker_latlng = new google.maps.LatLng(v.latitude, v.longitude); 


    markers[i] = new google.maps.Marker({ 
    position: marker_latlng, 
    map: map, 
    title:"here is my title" + v.id 
    }); 


    infowindows[i] = new google.maps.InfoWindow({ 
    content: "here is some content string" + v.id, 
    }); 

    google.maps.event.addListener(markers[i], 'click', function() { 
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i); 
    infowindows[i].open(map,markers[i]); 
    }); 
    i++; 
}); 

THX

回答

2

是否警报告诉你,值始终是181?您需要包装在封闭的处理程序声明中使用的i外在价值(这将永远是181次循环完成)

(function(i){ 
    google.maps.event.addListener(markers[i], 'click', function() { 
     alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i); 
     infowindows[i].open(map,markers[i]); 
    }); 
    }(i)); 

编辑阻止它:因为你使用jQuery的$。每个功能,它为每个迭代提供了自己的范围(因为每次迭代都调用一个函数),您还可以通过创建一个局部变量(例如j)来获取i的外部值,从而解决问题。

var j = i; 
    google.maps.event.addListener(markers[i], 'click', function() { 
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + j); 
    infowindows[j].open(map,markers[j]); 
    }); 

(这工作,因为每次迭代新j被创建,而你只有1 i之前,因为你宣布它的迭代函数外)。

2

修订

$.each(in_locations, function(i, item){ 
    console.log(i); 
    var marker_latlng = new google.maps.LatLng(item.latitude, item.longitude); 


    var markers = new google.maps.Marker({ 
    position: marker_latlng, 
    map: map, 
    title:"here is my title" + item.id 
    }); 


    var infowindows = new google.maps.InfoWindow({ 
    content: "here is some content string" + item.id, 
    }); 

    google.maps.event.addListener(markers, 'click', function() { 
    alert('number of infowindows: ' + in_locations.length + ' and value is: ' + i); 
    infowindows.open(map, markers); 
    }); 
}); 
  • 解释?你已经是一个循环里面$.each,所以你并不需要增加一个i++迭代
+0

出于某种原因,该的addListener不开火这个。可能有一个次要问题,我没有抓住。让我再看看这个。 thx回答 – timpone 2012-03-28 16:21:36

+0

更新与演示 – 2012-03-28 16:22:25

+0

thx aSeptik,这绝对奏效 - 选择其他答案,因为我正在做一些其他的东西与我的变量。真的很欣赏,因为我刚刚陷入困境。我相信我会有其他问题,并会很乐意接受 - 他们只是非常接近 – timpone 2012-03-28 16:39:55