谷歌地图地理编码器返回状态

2024-02-06

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

我认为问题实际上是地址组件可能有多个组成部分,并且所有邮政编码的顺序不一定相同。因此,您必须迭代结果才能找到正确的结果。

<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

谷歌地图地理编码器返回状态 的相关文章

随机推荐