2014-11-16 4 views
0

Google지도에 마커를 추가하려고하는데 이러한 마커에 숫자가 표시되지만 루프를 통해 반복되는 동일한 마커가 표시되는 이유는 무엇입니까? 여기에 내 코드,자바 스크립트에서 반복적으로 예상치 못한 결과가 발생합니다.

function codeAddress() { 
var address = ['hd3 3nn', 'hd6 3qf']; 
for (var i = 0; i < address.length; i++) { 
    var num = i; 
    geocoder.geocode({ 'address': address[i]}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png', 
        new google.maps.Size(20, 34), 
        new google.maps.Point(0, 0), 
        new google.maps.Point(10, 34)); 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: map, 
       icon: image, 
       position: results[0].geometry.location 
      }); 
     } else { 
      alert('Geocode was not successful for the following reason: ' + status); 
     } 
    }); 
} 

은}입니다

기본적으로이/~ 유방/WP - 콘텐츠/테마/m/IMG/마커/마커 '+ NUM +'.png를 만들고있다,/~ 유방/wp-content/themes/m/img/markers/marker1.png 하나는 마지막 루프의 번호이며 이전 아이콘 이미지를 모두 덮어 쓰는 것 같습니다.

+0

코드에 아무런 이상이 보이지 않습니다. marker.icon = new google.maps.MarkerImage (..)를 사용하여 마커와 함께 이미지를 만들 수 있습니까? 그런 다음 테스트에서 var count = 0을 만들고 루프에서 i를 사용하는 대신 이미지를 증가시킵니다. –

+1

@loanburger 문제는 루프의 각 패스에서 생성 된 함수가 외부 함수에 저장된 값과 동일한 'num' 변수에 계속 액세스한다는 것입니다. – Stuart

+0

응원하는 스튜어트가 답을 제시 할 때 아래에 나와 있습니다. 앞의 코드를 다시 살펴보면이 기능을 별도의 기능으로도 수행했습니다. –

답변

1

이것은 how Javascript closures work입니다.

콜백 함수를 반환하는 별도의 함수를 만들어이 문제를 해결할 수 있습니다.

function codeAddress() { 
    var address = ['hd3 3nn', 'hd6 3qf']; 
    for (var i = 0; i < address.length; i++) { 
     geocoder.geocode({'address': address[i]}, getGeocoderCallBack(i)); 
    } 
} 

function getGeocoderCallback(num) { 
    return function (results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var image = new google.maps.MarkerImage('/~udders/wp-content/themes/muslenh2/img/markers/marker' + num + '.png', 
      new google.maps.Size(20, 34), 
      new google.maps.Point(0, 0), 
      new google.maps.Point(10, 34)); 
      map.setCenter(results[0].geometry.location); 
      var marker = new google.maps.Marker({ 
       map: map, 
       icon: image, 
       position: results[0].geometry.location 
      }); 
     } else { 
      alert('Geocode was not successful for the following reason: ' + status); 
     } 
    }; 
} 
관련 문제