开发者

google maps geocoder to return state

I am using google maps geocoder to geocode a zipcode and I want it to return the state that the zipcode is located in and store it in the variable "local". I am getting an er开发者_开发百科ror indicating that local is undefined. Why?

see code below:

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


I think the issue is actually that address_components will likely have more than one component, and the order isn't necessarily the same for all zip codes. So you have to iterate through the results to find the correct one.

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


Where are checking value of the variable local? I haven't seen it in your code sample.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜