【问题标题】:Cannot collect alle results of asynchronous call with geo.getLocations (Google Maps)无法使用 geo.getLocations 收集异步调用的所有结果(谷歌地图)
【发布时间】:2009-06-25 13:42:39
【问题描述】:

下面是我的代码。问题是,无论我尝试什么,recordsOut[0] 始终是未定义的。

我知道这与回调结果有关。我试图添加一些延迟,以便有更多时间返回结果,但这没有帮助。

有什么想法(请举例)?非常感谢。

function getAddress(id, searchValue) {
    geo.getLocations(searchValue, function(result) {
        if (result.Status.code == G_GEO_SUCCESS) {
            var recordsOutStr = id + ';' + searchValue + ';';
            for (var j = 0; j < result.Placemark.length; j++)
                recordsOutStr += result.Placemark[j].address + ';' + result.Placemark[j].Point.coordinates[0] + ';' + result.Placemark[j].Point.coordinates[1];
            recordsOut.push(recordsOutStr);
            alert(recordsOutStr);
        }
        else {
            var reason = "Code " + result.Status.code;
            if (reasons[result.Status.code])
                reason = reasons[result.Status.code]
            alert('Could not find "' + searchValue + '" ' + reason);
        }
    });   
}

function delay(ms) 
{
  var date = new Date();
  var curDate = null;
  do 
  { 
    curDate = new Date(); 
  }
  while (curDate - date < ms);
} 

function processData()
{
   objDataIn = document.getElementById("dataIn");
   objDataOut = document.getElementById("dataOut");

   if (objDataIn != null)
   {
       //alert(objDataIn.value);
       if (objDataOut != null) {

           recordsIn = explode(objDataIn.value, ';', true);
           //for (i = 0; i < recordsIn.length; i++)
           for (i = 0; i <= 5; i++) 
           {
               addressStr = recordsIn[i]['address'] + ', ' +
                            recordsIn[i]['postalcode'] + ' ' +
                            recordsIn[i]['city'] + ', ' +
                            recordsIn[i]['country'];
               getAddress(recordsIn[i]['id'], addressStr); //This will set resultStr
               delay(200);
           }
           delay(5000);
           alert('***' + recordsOut[0] + '***');
           alert('***' + recordsOut[1] + '***');
           alert('***' + recordsOut[2] + '***');
           alert('***' + recordsOut[3] + '***');
           alert('***' + recordsOut[4] + '***');
       }
   }
   document.frmGeoCoder.submit();
}

【问题讨论】:

    标签: javascript google-maps loops callback


    【解决方案1】:

    确保您已经像这样定义了 recordsOut:

    var recordsOut = [];
    

    如果你这样做 - var recordsOut; - 它将是未定义的。

    如果这对您不起作用,请发布其余代码,以便我们确切了解发生了什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      相关资源
      最近更新 更多