2012-01-22 3 views
2

다음 문제가 발생하면 정보 창에 다른 마커에서 같은 결과가 나타납니다. 외부에서 디버깅 할 때 geocoder.geocode 함수는 올바른 정보를 표시하지만 항상 항상 같은 정보를 표시합니다. suppid 부분은 내가 올바른 변수 값을 보여주는 내부 변수를 디버깅 할 때입니다.Google지도 정보창에서 다른 마커에서 같은 결과가 나타납니다

var optionMap = { 
      zoom: 16, 
      MapTypeId: google.maps.MapTypeId.ROADMAP, 
      panControl: false, 
      zoomControl: false, 
      mapTypeControl: false, 
      scaleControl: false, 
      streetViewControl: false, 
      overviewMapControl: false 
     }; 

     var map = new google.maps.Map(document.getElementById('map'), optionMap); 

     var geocoder = new google.maps.Geocoder(); 

     var latlngbounds = new google.maps.LatLngBounds(); 

     var icon = new google.maps.MarkerImage('images/gm_pin.png', 
     new google.maps.Size(20, 34), 
     new google.maps.Point(0,0), 
     new google.maps.Point(10, 34)); 

     for(var i = 0; i < arrAddress.length; i++) { 

      var address = arrAddress[i]; 

      var html_title = "<div class='info'><h4>" + address + "</h4></div>"; 

      geocoder.geocode({ 
       'address': address 
      }, function (results, status) { 

       if(status == google.maps.GeocoderStatus.OK) { 


        var marker = new google.maps.Marker({ 
         map: map, 
         icon: icon, 
         html: html_title, 
         position: results[0].geometry.location 
        }); 

        var contentString = ''; 

        var infoWindow = new google.maps.InfoWindow({ 
         content: contentString 

         }); 

        google.maps.event.addListener(marker, 'mouseover', function() { 
         infoWindow.setContent(this.html); 
         infoWindow.open(map, this); 
        }); 

        google.maps.event.addListener(marker, 'mouseout', function() { 
         infoWindow.close(map, this); 
        }); 

        latlngbounds.extend(results[0].geometry.location); 

        if(i == arrAddress.length) { 
         map.fitBounds(latlngbounds); 
        } 

        google.maps.event.trigger(map, 'resize') 
       } 
      }); 
     } 

답변

3

Geocoder.geocode(request, callback)is asynchronous으로 전화하십시오. 서버가 응답하면 콜백 함수가 호출됩니다. 보통이 시간까지는 for 루프가 이미 완료되었습니다. 이는 정확히 사용자가 설명하는 결과를 나타낼 수 있습니다. 마커는 루프가 끝난 후 발생하는 콜백에서 작성되므로 html_title에 있던 마지막 값을 사용하므로 각 마커의 내용은 동일합니다.

이 문제를 해결하려면 루프 내부에 변수 html_title을 '캡처'하는 클로저를 만들어야합니다. 이렇게하면 콜백은 html_title의 올바른 값을 사용합니다.

자바 스크립트에서 일반적인 명시 적 폐쇄는 다음과 같습니다 노력이 고맙습니다

for(var i = 0; i < arrAddress.length; i++) { 
    var address = arrAddress[i]; 
    var html_title = "<div class='info'><h4>" + address + "</h4></div>"; 

    (function(address, title) { 
    // Inside the closure, we can use address and html_title 
    geocoder.geocode({'address': address /* captured */}, function (results, status) { 
     if(status == google.maps.GeocoderStatus.OK) { 
     var marker = new google.maps.Marker({ 
      map: map, 
      icon: icon, 
      html: title, /* captured */ 
      position: results[0].geometry.location 
     }); 

     var contentString = ''; 
     var infoWindow = new google.maps.InfoWindow({ 
      content: contentString 
     }); 

     // ... 
     } 
    }); 
    })(address, html_title); // <- Call function, pass the vars to be captured 
} 
+0

, 하나 개의 질문을 :

코드에서
// Wrap a function in() and immediately call it with another() // Pass in the arguments in the second() // This causes them to be 'captured' inside the function (function(args) { /* Do something with args */ })("Hello", 42); 

, 폐쇄 루프시에 주소를 캡처해야합니다 나는 그것도 별도의 기능에 넣을 수 있습니까? – mebots

+0

기술적으로 그것은 이미 별도의 기능입니다. 그래서 네, 명명 된 함수로 이동하고 루프 내부에서 해당 함수를 호출 할 수 있습니다. –

관련 문제