Google Maps Geocode-处理异步调用

时间:2014-07-13 20:25:32

标签: javascript html5 google-maps google-geocoder 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);
        }
    });
 }

我有一个调用此按钮的按钮,每次按下该按钮到文本文件中的下一个地址时,我都会尝试更新地图。我遇到一些问题,它是异步的,并且不一定按此顺序运行。我很难想到解决这个问题的方法,任何想法?

1 个答案:

答案 0 :(得分:1)

为什么不在xhr.onreadystatechange事件中调用地理编码?

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:我真的建议你在可行的情况下用jQuery做Ajax。大多数时候重新发明轮子并不好。 http://learn.jquery.com/ajax/