Google Maps Geocode-处理异步调用



我有代码:

 function mapNextAddress() {
    var xhr, i, text, lines, address;
    if(window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari
        xhr = new XMLHttpRequest();
    }
    else
    {
        // IE5, IE6  - next line supports these dinosaurs
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = function()
    {
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            text = xhr.responseText;
            lines = text.split("n"); 
            address = lines[numberAddress];
            numberAddress = numberAddress + 1;
        }
    }
    xhr.open("GET","OFCaddresses.txt",true);
    xhr.send();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
          });
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
    });
 }

我有一个按钮,调用这个,我试图更新地图每次按钮被点击到文本文件中的下一个地址。我有一些问题的事实,它是异步的,它不一定是按这个顺序运行。我被困在试图想出一个变通办法,有什么想法吗?

为什么不在xhr.onreadystatechange事件中调用geocode呢?

xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        text = xhr.responseText;
        lines = text.split("n"); 
        address = lines[numberAddress];
        numberAddress = numberAddress + 1;
        doGeocode();
    }
}

doGeocode函数的逻辑没有修改

function doGeocode() {
    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
});

PS:我真的建议你做Ajax的东西与jQuery如果可行的话。大多数时候,重新发明轮子并不是件好事。http://learn.jquery.com/ajax/

最新更新