谷歌地图的问题API反向地理编码 - 邮政编码仅返回2(前缀)

时间:2013-07-11 19:23:40

标签: php google-maps reverse-geocoding

我有这个php从谷歌服务器获取有关特定地理位置的数据。

<?php
if ($_GET['latitude'] AND $_GET['longitude']) {
    $lat = $_GET['latitude'];
    $lng = $_GET['longitude'];
    echo json_encode(reverse_geocode($lat,$lng));
}
?>


<?php
//Get STATE from Google GeoData
function reverse_geocode($lat,$lng) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false";
    $result = file_get_contents("$url");
    $json = json_decode($result);
    foreach ($json->results as $result) {
        foreach($result->address_components as $addressPart) {
            //print_r($addressPart);
            if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {
                $city = $addressPart->long_name;
            }
            else if((in_array('administrative_area_level_1', $addressPart->types)) && (in_array('political', $addressPart->types))) {
                $state = $addressPart->long_name;
            }
            else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {
                $country = $addressPart->long_name;
            }
            else if(in_array('route', $addressPart->types)) {
                $street = $addressPart->long_name;
            }
            else if(in_array('street_number', $addressPart->types)) {
                $street_number = $addressPart->long_name;
            }
            else if(in_array('postal_code', $addressPart->types)) {
                $postal_code = $addressPart->long_name;
            }
        }
    }

    //return $address;
    return array('country' => $country, 'state' => $state, 'city' => $city, 'street' => $street_number . " " . $street, 'zip' => $postal_code);
    //print_r($json);
}
?>

?latitude=49.260441796677014&longitude=-123.12049284766846

返回:

{"country":"Canada","state":"British Columbia","city":"Vancouver","street":"706-750 West 12th Avenue","zip":"V5Z"}

注意zip,它是邮政编码的3个字母前缀,而不是真正的邮政编码。为什么会这样?在原始的json数据中,我似乎有完整的邮政编码。取消注释print_r($addressPart);以查看我在说什么。

1 个答案:

答案 0 :(得分:2)

$addressPart取自postal_code的{​​{1}}包含postal_code类型,但当您检查回复时,您会看到它还包含{{1}类型那就是你得到的东西。当类型包含postal_code_prefix

时,请跳过$addressPart
postal_code_prefix