2011-07-12 18 views
0

郵便番号から都市名を取得するためにGoogle Maps APIを使用しようとしています。これは私の強みではありません(私はPHPの方です)、サンプルコードを使用しています。変数の読み込み中にGoogle Maps APIの遅延が発生する

問題は、関数を呼び出すと、都市名のグローバル変数が初期値のnullになっているということです。しかし、この値でアラートを出した場合、処理の残りの部分には突然正しい値がロードされます。私は時間の遅れを入れて、Googleが価値を返すのが遅かったかどうかを見てみましたが、違いはありません。

ここでは、関数の:

var geocoder = new google.maps.Geocoder(); 
function getGoogleAddress(zipcode) { 
    //var gcity = "N/A"; switch to using global var defined above 
    geocoder.geocode({ 'address': zipcode}, function (result, status) { 
     for (var component in result[0]['address_components']) { 
      for (var i in result[0]['address_components'][component]['types']) { 
       if (result[0]['address_components'][component]['types'][i] == "locality") { 
        gcity = result[0]['address_components'][component]['short_name']; 
        break; 
       } 
      } 
     } 
    }); 
} 

そして、それが呼び出されます場所です...警告と一時停止を含む:

 gcity=""; 
     getGoogleAddress(form.zip.value); 
     var holdcity = gcity; 
     var date = new Date(); 
     var curDate = null; 
     do { curDate = new Date(); } 
     while(curDate-date < 2000); 
     alert(gcity); 

私が言ったように、アラートはnullを返しますが、残りの処理では、適切な都市名がgcityにあります。アラートを除外すると、gcityがnullであるため残りの処理は失敗します。

アドバイスやご提案をいただければ幸いです。ありがとう。

+1

ヒント:AJAXでの "A" は非同期」の略です。 "この質問は、1つの形式または別の形で、毎日少なくとも5回尋ねられます。 –

答えて

1

非同期。

function (result, status) {は、Googleのサーバーが応答したときにのみ実行されます。 getGoogleAddress関数の残りの部分はそれを待たずに終了し、JavaScriptはvar holdcity = gcityで実行を続けます。

alertの後は、Googleが応答し、gcity変数が実行されます。

考えられる解決策:

var geocoder = new google.maps.Geocoder(); 
function getGoogleAddress(zipcode, successFunction) { 
    //var gcity = "N/A"; switch to using global var defined above 
    geocoder.geocode({ 'address': zipcode}, function (result, status) { 
     for (var component in result[0]['address_components']) { 
      for (var i in result[0]['address_components'][component]['types']) { 
       if (result[0]['address_components'][component]['types'][i] == "locality") { 
        var gcity = result[0]['address_components'][component]['short_name']; 
        successFunction(gcity); 
        break; 
       } 
      } 
     } 
    }); 
} 

そして、それが呼び出されますこれはどこで...警告と一時停止を含む:

getGoogleAddress(form.zip.value, function (holdcity) { 
     var date = new Date(); 
     var curDate = null; 
     do { curDate = new Date(); } 
     while(curDate-date < 2000); 
     alert(holdcity); 
    }); 
+0

ありがとうございます...アラートは正常に機能しましたが、最初の問題が再発した直後です。私はgcity変数にholdcityを再割り当てし、警告を出さない限りは空白です。 – tzvishmuel

+0

getGoogleAddress関数のコードを外していると思いますか?そのコードは匿名の 'function(holdcity)'の前に実行されるので、これはうまくいきません。別の関数で 'gcity'を使う場所にコードを置き、getGoogleAddressから呼び出す必要があります。 – Martijn

関連する問題