我最終自己解決了這個問題。我的解決方案採用城市列表並通過API調用對其進行地理編碼。當最後一次調用被帶回時,一個稱爲主運行的回調函數。 Main函數是您可以訪問已填充的lats和lons數組的地方。
//Here is an array of locations to be geocoded
var locations1 = [];
locations1.push("Horsham, PA");
locations1.push("Dallas, TX");
locations1.push("Chicago, IL");
locations1.push("Denver, CO");
locations1.push("San Diego, CA");
// Create an array to store the latitudes and longitudes
var lat1=[];
var lon1=[];
//create time parameter to delay each call, limited number of calls per
//second
var time=0;
//loop through each location and call the geo function
for (var i = 0; i < locations1.length; i++) {
geo(locations1[i],time);
time=time+1;
}
// inputs a location and time parameter then adds the lat/lon to array
function geo(loc,t){
var geocoder = new google.maps.Geocoder();
setTimeout(function(){
geocoder.geocode({
'address': loc
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat1.push(results[0].geometry.location.lat());
lon1.push(results[0].geometry.location.lng());
} else {
alert("Something got wrong " + status+ " problem with: "+ loc);
}
// When your array is full run main, this is where you can do
//things with the array
if(lat1.length==locations1.length){
main();
}
});
},t*1000);
}
function main(){
for(var j=0;j<lat1.length;j++){
alert(locations1[j]+" has latitude of "+lat1[j]+", and longitude of
"+lon1[j]);
// do what ever else you want to do with the populated array
}
}
這裏是擁有所有的代碼小提琴:
http://jsfiddle.net/sharder14/afkzv2fx/
是'geocode'方法同步?或者它是異步的? –
您正試圖訪問尚未定義的變量。這是因爲'geocoder.geocode'中的'callback'函數尚未被調用。所以你得到'undefined'。試着在'else'聲明的右括號之後立即替換你的提醒 - 然後你會看到你的電話號碼 –
感謝您的快速響應!它仍然沒有工作。顯然它是異步的。另外,如果我在else語句之後立即發出警報,警報就會起作用,但它們不會位於地理編碼塊外(這是我需要訪問它們的地方) –