2013-09-26 5 views
0

약간의 문제가 있습니다. 마크의 제목을 제외한 모든 것이 제대로 작동하는 다음 코드가 있습니다. 항상 배열 목록의 마지막 제목을 표시합니다. 누군가 왜이 오류를 알고 있습니까?Google지도 여러 마커

코드 :

$(document).ready(function() { 

      var options = { 
       zoom: 7, 
       center: new google.maps.LatLng(42.19708, 2.19075), 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       mapTypeControl: true 
      }; 

      var geocoder = new google.maps.Geocoder(); 
      var map = new google.maps.Map(document.getElementById('map_canvas'), options); 

      var companys = [ 
       ['Giga S.L', 'Plaça de Catalunya, Barcelona'], 
       ['Torre M', 'Plaça d\'Espanya, Barcelona'] 
      ]; 

      var address; 
      var title; 

      for (var i = 0; i < companys.length; i++) { 
       address = companys[i][1]; 
       title = companys[i][0]; 

       geocoder.geocode({'address': address}, function(results, status) { 
        if (status === google.maps.GeocoderStatus.OK) { 
         map.setCenter(results[0].geometry.location); 

         new google.maps.Marker({ 
          map: map, 
          animation: google.maps.Animation.DROP, 
          position: results[0].geometry.location, 
          title: title // ERROR: ALWAYS THE SAME TITLE 
         }); 
        } else { 
         alert('Geocode was not successful for the following reason: ' + status); 
        } 
       }); 
      } 
     }); 

미리 감사드립니다.

감사합니다.

답변

1

한 가지 방법은 매개 변수로 변수를 전달 immediately-invoked function expression (IFFE)에서 geocode에 대한 호출을 래핑하는 것입니다 :

(function(address, title) { // the variables are passed in here as function parameters 

    geocoder.geocode({'address': address}, function(results, status) { 
    if (status === google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 

     new google.maps.Marker({ 
     map: map, 
     animation: google.maps.Animation.DROP, 
     position: results[0].geometry.location, 
     title: title 
     }); 
    } else { 
     alert('Geocode was not successful for the following reason: ' + status); 
    } 
    }); 

}(address, title)); // pass in address/title into the IFFE 
+0

대단히 고마워요, 완벽하게 작동합니다! –

1

geocoder.geocode에는 콜백 기능이 있습니다. 이는 코드가 비동기 적으로 실행됨을 의미합니다. 콜백 내에서 회사 제목을 검색하도록 코드를 재구성해야합니다.

코드에서 geocode 콜백이 반환되기 전에 for 루프가 이미 완료되었으므로 변수 제목이 마지막으로 설정된 이유입니다. 이 문제를 해결하기 위해

+0

대단히 감사합니다! –