2009-12-03 2 views
2

저는 여러 국가의 여러 테스트 센터 위치가 포함 된 Google지도를 작성하고 있습니다. 각 카운티에 마커를 표시하고 카운티 마커를 클릭하면 확대되어 해당 카운티의 테스트 센터에 대한 개요를 제공합니다. 또한 jQuery를 사용하고 있습니다. 내가 카운티 마커를 음모하고 클릭하면Google지도 : 이벤트 리스너는 변수의 최종 값만 기억합니다.

, 항상 마지막 카운티에 확대 :

다음은 문제입니다. 다음과 같이 나는 군을 플롯 사용하고 코드는 다음과 같습니다

function plotCountyMarkers(county_count) 
{ 
    // Setup a new icon 
    var icon = new GIcon(); 
    var count = 0; 

    // Get the type of icon to display 
    var centre_type = checkCentreType(); 
    if (centre_type == 'dtc') 
     icon.image = dtc_icon; 
    else 
     icon.image = ctc_icon; 

    // Other settings including icon shadow 
    icon.shadow = icon_shadow; 
    icon.iconSize = new GSize(20, 29); 
    icon.shadowSize = new GSize(38, 29); 
    icon.iconAnchor = new GPoint(10, 29); 
    icon.infoWindowAnchor = new GPoint(10, 1); 

    // Get the total number of counties to map 
    var count = county_count.length; 

    for (key in county_count) { 
     // Set the LatLong of the county 
     var countyLocation = new GLatLng(county_locations[key][0],county_locations[key][1]); 
     // Set the title text of the marker 
     var centre_text = county_count[key]==1 ? 'Centre' : 'Centres'; 
     var title = county_locations[key][2]+': '+county_count[key]+' Test '+centre_text; 
     // Add an event listener to the marker 
     var marker = new GMarker(countyLocation,{icon: icon, title: title}); 

     GEvent.addListener(marker, "click", function() { 
      // Zoom to county 
      showCounty(key); 
     }); 

     // Add the marker to the map 
     map.addOverlay(marker); 
    } 
} 

을 당신이 현급 마커를 클릭하면에 대한 이벤트 리스너에 HTML을 전달하는 데 기본적으로 동일한 방법을 사용하고, 그 잘 작동합니다 . 어떤 이유로 인해 key은 항상 최종 카운티의 값입니다. 나는 함수에 변수로서 key을 전달하려고했지만, 현재지도의 경도와 위도와 동일하게된다.

어쩌면 나는 뭔가 바보 같은 짓을하고 있습니까? 그것은 처음되지 않을 것입니다 :) 어떤 도움을 많이 주시면 감사하겠습니다.

+0

참조 http://stackoverflow.com/questions/1331769/ http://stackoverflow.com/questions/1451009/javascript -infamous-loop-problem http://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure http://stackoverflow.com/questions/1734749/ http :// /stackoverflow.com/questions/643542/ –

+0

또한 'foryin'이 아니라 'fory'를 사용하십시오.'county_count '를 반복 할 때. –

답변

4

건배, 나는 다음에 이벤트 핸들러를 변경하고 일 :

GEvent.addListener(marker, "click", 
    (function(key) { 
     return function() { 
      // Zoom to county 
      showCounty(key); 
     }; 
    })(key) 
); 
+1

좋습니다! 당신은 실제로 제가 게시 한 링크 중 일부를 읽었습니까? –

관련 문제