日期:2014-05-16  浏览次数:20300 次

javascript的函数调用,谁来救救我啊!
本帖最后由 liangddmy 于 2013-10-29 10:47:17 编辑
这是一个调用Google Maps获取地理编码的程序,但是我发现for循环的执行过程很诡异,总是先执行alert(locationArr);打印一个空的数组,然后再执行codeAddress函数得到正确的编码,谁能告诉我这种违反我的常识的情况是怎么来的?如何解决呢?
for(j=0;j<stationNum;j++){
locationArr[j]=codeAddress(stationArr[j]);
}
alert(locationArr);

function codeAddress(addressStr){
var geocoder = new google.maps.Geocoder();
var reLocation=new google.maps.LatLng();
geocoder.geocode( { 'address': addressStr}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {       
  reLocation=results[0].geometry.location;
  } else {
  reLocation=null;
  }
});
                alert(reLocation);
return reLocation;
}
javascript google?maps

------解决方案--------------------
本帖最后由 showbo 于 2013-10-29 11:28:21 编辑
   var j = 0;
    function codeAddress(addressStr) {
        var geocoder = new google.maps.Geocoder();
        var reLocation = new google.maps.LatLng();
        geocoder.geocode({ 'address': addressStr }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                locationArr[j] = results[0].geometry.location;
            } else {
                locationArr[j] = null;
            }
//单个地址解码后操作这个地址对应的代码放这里来

            j++;
            if (j < stationArr.length) codeAddress(stationArr[j]);
            else{ 如果是对locationArr进行整体操作要放这里}
        });
    }
    codeAddress(stationArr[j]);