3

Google マップ ジオコーダーを使用して郵便番号をジオコーディングしています。郵便番号が存在する状態を返し、それを変数 "local" に格納する必要があります。local が未定義であることを示すエラーが表示されます。なんで?

以下のコードを参照してください。

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);
}
});
4

2 に答える 2

5

問題は、実際にはaddress_componentsに複数のコンポーネントが含まれる可能性が高く、すべての郵便番号で順序が必ずしも同じであるとは限らないことだと思います。そのため、正しい結果を見つけるために結果を反復処理する必要があります。

<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>
于 2011-07-21T22:55:41.460 に答える
0

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

コールバック関数がない場合は、何も奇妙なことはありません。ジオコーダーへのリクエストは非同期で実行されます。そのため、リクエストを実行した後でも未定義になる可能性があります。変数で動作するコードをコールバック関数に入れる必要がありlocalます。

于 2011-07-23T09:53:15.283 に答える