2013-09-26 72 views
0

我有一個小問題,我有下面的代碼,顯然一切工作正常,除了標記的標題。它總是顯示數組列表的最後一個標題。有人知道爲什麼這個錯誤?谷歌地圖多個標記

代碼:

$(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

一個解決這種方式來包裝調用geocodeimmediately-invoked function expression(IFFE),在您的變量傳遞的參數:

(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

非常感謝您! –