【问题标题】:Google Maps Geocode- dealing with the asynchronous callGoogle Maps Geocode - 处理异步调用
【发布时间】:2014-07-13 20:25:32
【问题描述】:

我有代码:

 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);
        }
    });
 }

我有一个调用此按钮的按钮,每次单击该按钮到文本文件中的下一个地址时,我都会尝试更新地图。我遇到了一些问题,即它是异步的并且不一定按此顺序运行。我一直在想办法解决这个问题,有什么想法吗?

【问题讨论】:

    标签: javascript html google-maps google-geocoder geocode


    【解决方案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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多