Google maps api 3 谷歌地图地理编码器返回状态

Google maps api 3 谷歌地图地理编码器返回状态,google-maps-api-3,geocode,Google Maps Api 3,Geocode,我正在使用google maps geocoder对zipcode进行地理编码,我希望它返回zipcode所在的状态,并将其存储在变量“local”中。我收到一个错误,表明本地未定义。为什么? 见下面的代码: var address=document.getElementById("address").value; var radius=document.getElementById("radius").value; var latitude=40; var longitude=0; var l

我正在使用google maps geocoder对zipcode进行地理编码,我希望它返回zipcode所在的状态,并将其存储在变量“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);
}
});

我认为问题实际上是地址组件将可能有多个组件,并且并非所有邮政编码的顺序都相同。因此,您必须遍历结果以找到正确的结果

<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>

var geocoder=new google.maps.geocoder();
功能测试()
{
var address=document.getElementById(“地址”).value;
var local=document.getElementById(“本地”);
纬度=40;
var经度=0;
geocoder.geocode({'address':address},函数(结果,状态)
{
if(status==google.maps.GeocoderStatus.OK)
{
latlng=(结果[0]。几何体。位置);
纬度=latlng.lat();
经度=latlng.lng();
//将状态缩写存储在局部变量中
对于(var ix=0;ix
在哪里检查变量的值
local
?我在您的代码示例中没有看到它

如果退出了回调函数,那么就没有什么奇怪的了。对地理编码器的请求以异步方式运行。因此,即使在运行请求之后,它也可能是未定义的。您需要将使用变量
local
的代码放入回调函数中