Problems with async geocoder.geocode
I'm having trouble getting the position of an address. However, this problem occurs only the first time that I run, ie it is necessary that every time I make the query, I click twice, for only the second values are obtained.
I believe the problem is due to be asynchronous method. But I am not able to solve the problem. Some of his friends could help me.
$('#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;
开发者_如何学C } 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();
}
});
Solution:
$('#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();
}
});
}
});
}
});
精彩评论