2013-11-27 17 views
1

下面的代码每次运行while循环时都会覆盖var存储区。所以当回调运行时,商店值通常是商店数组中的最后一个商品。如何将值添加到回调函数中的正确对象?

var stores = []; 
stores.push({'address': "1 California Ave, San Francisco, CA"}); 
stores.push({'address': "16 California Ave, San Francisco, CA"}); 
stores.push({'address': "20 California Ave, San Francisco, CA"}); 
stores.push({'address': "30 California Ave, San Francisco, CA"}); 

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

var i = 0; 
while(i < stores.length){ 
    var store = stores[i]; 
    geocoder.geocode({'address':store.fullAddress}, function(data, status){ 
      store.latlng = data[0].geometry.location; 
      } 
     }); 
    i++; 
}; 

如何将正确的latlng添加到正确的商店?

这不起作用,因为var i也会改变。

var i = 0; 
var storesObject = {} 
while(i < stores.length){ 
    var store = stores[i]; 
    storesObject[i] = stores[i]; 
    geocoder.geocode({'address':store.fullAddress}, function(data, status){ 
      storesObject[i].latlng = data[0].geometry.location; 
      } 
     }); 
    i++; 
}; 

如果我这样做,我该如何将结果与商店数组相匹配?

var i = 0; 
var results = []; 
while(i < stores.length){ 
    var store = stores[i]; 
    geocoder.geocode({'address':store.fullAddress}, function(data, status){ 
      results.push(data[0].geometry.location); 
      } 
     }); 
    i++; 
}; 

更新的功能范围将固定我的问题:

var i = 0; 
while(i < stores.length){ 
    (function(){ 
    var store = stores[i]; 
    geocoder.geocode({'address':store.fullAddress}, function(data, status){ 
      store.latlng = data[0].geometry.location; 
      } 
    }); 
    })(); 
    i++; 
}; 

见: GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?

+0

http://stackoverflow.com/questions/10555097/gmaps-js- geocode-using-passing-variables-with-asynchronous-geocode-function?rq = 1在功能范围内回答我的问题。我应该关闭这个问题吗? – ChickenFur

+0

它最终可能会作为重复被关闭。我会离开它,因为人们仍然能够找到它,并且您的头衔可能会抓住一些搜索。 – Pointy

回答

1
function geocodeAddress(store) { 
    geocoder.geocode({'address':stores[store].address}, function(data, status){ 
    if (status == google.maps.GeocoderStatus.OK) { 
     stores[store].latlng = data[0].geometry.location; 
    } else { 
     alert("Geocode failed: " + status); 
    } 
    }); 
} 
var stores = []; 
stores.push({'address': "1 California Ave, San Francisco, CA"}); 
stores.push({'address': "16 California Ave, San Francisco, CA"}); 
stores.push({'address': "20 California Ave, San Francisco, CA"}); 
stores.push({'address': "30 California Ave, San Francisco, CA"}); 

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

var i = 0; 
while(i < stores.length){ 
    geocodeAddress(i); 
    i++; 
}; 
相关问题