2011-07-21 13 views
3

Googleマップジオコーダーを使用して郵便番号をジオコードすると、郵便番号が格納されている状態を返して変数 "local"に格納します。ローカルが未定義であることを示すエラーが表示されます。どうして?私は問題がaddress_components可能性が高い複数のコンポーネントを持つことになりますし、順番は必ずしもすべての郵便番号のために同じではないこと実際にあると思いgoogle mapsジオコーダーで状態を返す

var address=document.getElementById("address").value; 
var radius=document.getElementById("radius").value; 
var latitude=40; 
var longitude=0; 
var local; 
geocoder.geocode({ 'address': address}, function(results, status){ 
if (status==google.maps.GeocoderStatus.OK){ 
latlng=(results[0].geometry.location); 
latitude=latlng.lat(); 
longitude=latlng.lng(); 
//store the state abbreviation in the variable local 
local=results[0].address_components.types.adminstrative_area_level_1; 
} 

else{ 
    alert("Geocode was not successful for the following reason: " + status); 
} 
}); 

答えて

5

は、以下のコードを参照してください。正しい結果を見つけるためには、結果を繰り返し処理する必要があります。

<html xmlns="http://www.w3.org/1999/xhtml"> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
var geocoder = new google.maps.Geocoder(); 
function test() 
{ 
    var address=document.getElementById("address").value; 
    var local = document.getElementById("local"); 
    var latitude=40; 
    var longitude=0; 
    geocoder.geocode({ 'address': address}, function(results, status) 
    { 
     if (status==google.maps.GeocoderStatus.OK) 
     { 
      latlng=(results[0].geometry.location); 
      latitude=latlng.lat(); 
      longitude=latlng.lng(); 
      //store the state abbreviation in the variable local 
      for(var ix=0; ix< results[0].address_components.length; ix++) 
      { 
       if (results[0].address_components[ix].types[0] == "administrative_area_level_1") 
       { 
        local.value=results[0].address_components[ix].short_name; 
       } 
      } 
     } 
     else 
     { 
      alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
} 
</script> 
</head> 
<body> 
    <input type='text' id='address' value='84102' /> 
    <input type='text' id='local' value='' /> 
    <a href='#' onclick="test();" >try</a> 
</body> 
</html> 
0

ここで、変数localの値をチェックしていますか?私はあなたのコードサンプルでそれを見たことがありません。

コールバック関数から外れている場合、何も変わりません。ジオコーダーへの要求は非同期に実行されます。したがって、リクエストを実行しても定義されていない可能性があります。変数localで動作するコードをコールバック関数に入れる必要があります。

関連する問題