2010-06-28 74 views
1

我无法获取地址的位置。但是,这个问题只会在我第一次运行时发生,也就是说,每次我进行查询时,都需要点击两次,因为只有第二个值才能获得。异步geocoder.geocode问题

我相信问题是由于是异步方法。但我无法解决问题。他的一些朋友可以帮助我。

$('#btnTracar').click(function(){ 
if (geocoder){ 
    geocoder.geocode({ 'address': document.getElementById('txtStart').value }, function(results, status){ 
     if (status == google.maps.GeocoderStatus.OK) { 
      mapStart = results[0].geometry.location; 
     } else { alert("Não foi possível carregar a localização. \nDescrição do Erro: " + status); } 
    }); 

    geocoder.geocode({ 'address': document.getElementById('txtEnd').value }, function(results, status){ 
     if (status == google.maps.GeocoderStatus.OK) { 
      mapEnd = results[0].geometry.location; 
     } else { alert("Não foi possível carregar a localização. \nDescrição do Erro: " + status); } 
    }); 

    calcularRota(); 
} 
}); 

回答

1

解决方案:

 $('#btnTracar').click(function(){ 
      if ($.trim($("#txtStart").val()) == ""){ 
       alert("Favor preencher o campo de Origem Corretamente."); 
       return; 
      } 

      if ($.trim($("#txtEnd").val()) == ""){ 
       alert("Favor preencher o campo de Origem Corretamente."); 
       return; 
      } 

      if (geocoder){ 
       geocoder.geocode({ 'address': document.getElementById('txtStart').value }, function(results, status){ 
        if (status == google.maps.GeocoderStatus.OK){ 
         mapStart = results[0].geometry.location; 
         geocoder.geocode({ 'address': document.getElementById('txtEnd').value }, function(results, status){ 
          if (status == google.maps.GeocoderStatus.OK){ 
           mapEnd = results[0].geometry.location; 
           calcularRota(); 
          } 
         }); 
        } 
       }); 
      } 
     });