2012-03-28 2 views
0

다음 코드가 있습니다. 마커 중 하나를 클릭 할 때마다 첫 번째 정보 창이 나타납니다. 나는 181 개의 정보원과 181 개의 마커를 가지고있다. 어떤 도움을 주셔서 감사합니다.Google지도 - 왜 항상 첫 번째 정보창을 얻고 있는지 잘 모르겠습니다

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++; 
}); 

들으

답변

2

을 증가 할 필요가 없습니다? 당신은 (루프가 완료되면 항상 181 예정) i의 외부 값

(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의 $ .each 기능을 사용하고 있기 때문에, (각 반복이 함수를 호출하기 때문에) 각 반복마다 고유 한 범위를 제공하므로 j의 외부 변수를 가져 오는 로컬 변수 j를 생성하여 문제를 해결할 수도 있습니다.

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++ 반복자 경고가 값이 181이 항상 있음을 말해 주는가
+0

의의 addListener는에 발사되지 이. 내가 잡을 수없는 보조 문제가있을 수 있습니다. 이것 좀 더 살펴 보도록하겠습니다. 대답 – timpone

+0

은 –

+0

thx aSeptik으로 업데이트되었습니다.이 변수는 i 변수를 사용하여 다른 답변을했기 때문에 다른 답변을 선택했습니다. 내가 막 갇혔을 때 정말 고마워. 나는 다른 문제가있을 것이고 기꺼이 받아 들일 것이라고 확신한다. 그들은 매우 가까이에있다. – timpone

관련 문제