2012-01-26 4 views
0

私はJavaScriptにはとても新しいので、ジオコーダーのリクエストをタイムアウトする際に問題が発生しています。 しかし、私は立ち往生しています、私はループに遅延を追加しようとしますが、動作しないようです。 お手伝いできれば、私はそれを感謝します。JavaScriptを使用してGoogleマップジオコーダをタイムアウトするにはどうすればよいですか?

 <script type="text/javascript"> 

     function setLocationOnMap(locs) { 
      var myOptions = { 
       zoom: 4, 
       center: new google.maps.LatLng(locs.lat(), locs.lng()), 
       mapTypeId: google.maps.MapTypeId.ROADMAP   
      }; 
      var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); 

      var i=0; 
      var total='<?php echo $counter ?>'; 

      for (i=0; i<total;i++){//adding cities to map by 
       var city= document.the_form.elements[i].value; 

       getLatLong2(city, map, setPointer); 
      }     
     } 

     function setPointer(map, address, locs2){ 
      var position = new google.maps.LatLng(locs2.lat(), locs2.lng()); 
      var marker = new google.maps.Marker({ 
       position: position, 
       map: map 
      }); 
      marker.setTitle(address); 
     } 


     function initialize() { 
      var address = "Chicago IL"; 
      getLatLong(address, setLocationOnMap); 
     } 

     function getLatLong2(address, map, callback){ 
      var geo = new google.maps.Geocoder; 
      geo.geocode({'address':address},function(results, status){ 
       if (status == google.maps.GeocoderStatus.OK) { 
        locs2 = results[0].geometry.location; 

        callback(map, address, locs2); 
       } else { 
        //alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 
     } 



     function getLatLong(address, callback){ 
      var geo = new google.maps.Geocoder; 
      geo.geocode({'address':address},function(results, status){ 
       if (status == google.maps.GeocoderStatus.OK) { 
        // processing... 
        locs = results[0].geometry.location; 
        //pausecomp(10000); 

        callback(locs); 
       } else { 
        //alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 
     } 
    </script> 

答えて

2

ジオコード要求を送信すると、タイマーを並列に開始することができ、タイマーが起動すると、要求がタイムアウトしたことを宣言できます。依頼は引き続き行われますが、タイムアウトすると結果は無視されます。

function getLatLong(address, callback){ 
    var timerId; 
    var timedOut = false; 

    var geo = new google.maps.Geocoder; 
    geo.geocode({'address':address},function(results, status){ 
     if (timedOut) { 
      // this request timed out, so ignore results 
      return; 
     } else { 
      // this request succeeded, so cancel timer 
      clearTimeout(timerId); 
     } 

     if (status == google.maps.GeocoderStatus.OK) { 
      locs = results[0].geometry.location; 
      callback(locs); 
     } else { 
      //alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 

    timerId = setTimeout(function() { 
     timedOut = true; 
     alert('Request timed out.'); 
     // do something else 
    }, 10000); 
} 
関連する問題