2010-09-14 58 views
0

我使用http://tile.cloudmade.com/wml/latest/web-maps-lite.js進行地理編碼。拼圖:clousure中的值發生更改

有含約20個addresess

addresses[n] = {where:where,who:who,contact:contact,note:note,type:type}; 

然後我環路地址陣列的方向進行地理編碼

for (var i = 0; i < addresses.length; i++) { 
    geocoder2.getLocations(addresses[i].where, function(response) { //a callback 
     return function(k){ 
     Lat[k] = response.features[0].centroid.coordinates[0]; 
     Lng[k] = response.features[0].centroid.coordinates[1]; 
     latlng = new google.maps.LatLng(Lat[k], Lng[k]); 
     MarkerArray[k] = new google.maps.Marker({ 
      map: map, 
      position: latlng, 
      zIndex: k, 
      title: addresses[k].who, 
      icon: icons(addresses[k].type.trim()) 
     });}(i) // a closure function called 
    }); 
} 

但它始終工作在最終的指數。爲什麼??

回答

1

您有閉環問題。您似乎試圖通過添加return function(k)...閉包來修復它,但這些都發生在回調函數內部,所以直到循環退出並且i指向其最終值纔會執行。

你將不得不推的是包裝出來的水平所以它是直接在循環中:

for (var i = 0; i < addresses.length; i++) { 
    geocoder2.getLocations(addresses[i].where, function(k) { //a callback 
     return function(response){ 
      Lat[k] = response.features[0].centroid.coordinates[0]; 
      Lng[k] = response.features[0].centroid.coordinates[1]; 
      latlng = new google.maps.LatLng(Lat[k], Lng[k]); 
      MarkerArray[k] = new google.maps.Marker({ 
       map: map, 
       position: latlng, 
       zIndex: k, 
       title: addresses[k].who, 
       icon: icons(addresses[k].type.trim()) 
      }); 
     } 
    }(i)); // binding *here* instead! 
} 

或者使用Function#bind避免嵌套函數。

+0

你的封裝解決方案在Firefox中工作,但在IE和Chrome ....仍然有同樣的問題。我會花一些時間來看看綁定解決方案 – ValidfroM 2010-09-14 16:25:19

+0

非常奇怪,所有經緯度都是正確的,但只是標題和圖標是錯誤的... – ValidfroM 2010-09-14 16:27:06

相關問題