【问题标题】:google maps geocoder to return state谷歌地图地理编码器返回状态
【发布时间】:2011-07-21 15:01:38
【问题描述】:

我正在使用谷歌地图地理编码器对邮政编码进行地理编码,我希望它返回邮政编码所在的状态并将其存储在变量“本地”中。我收到一个错误,表明本地未定义。为什么?

见下面的代码:

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

【问题讨论】:

    标签: google-maps-api-3 geocode


    【解决方案1】:

    我认为问题实际上是 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>
    

    【讨论】:

      【解决方案2】:

      变量local的检查值在哪里?我没有在你的代码示例中看到它。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-21
        • 2015-05-20
        • 2012-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-23
        • 1970-01-01
        相关资源
        最近更新 更多