3

我正在使用谷歌地图地理编码器对邮政编码进行地理编码,我希望它返回邮政编码所在的状态并将其存储在变量“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?我在您的代码示例中没有看到它。

If out of the callback function, then nothing weird. Request to the geocoder runs asynchronously. So it could be undefined even after you run the request. You need to put code which works with variable local into callback function.

于 2011-07-23T09:53:15.283 回答