反向地理编码:获取城市和国家

时间:2015-11-03 19:44:44

标签: php reverse-geocoding

我想使用反向地理编码来获取坐标的城市和国家。

以下是两个例子:

Hamburg, Germany

Bangkok, Thailand

我始终需要第一个address_components,然后是价值为[ "locality" ][ "country", "political" ]的两种类型,但我不知道如何定位它们。

到目前为止我所拥有的:

$url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . get_wpgeo_latitude( $post_id ) . ',' . get_wpgeo_longitude( $post_id ) . '&language=de';
$data = @file_get_contents( $url );
$jsondata = json_decode( $data, true );

print_r( $jsondata['results'][0]['address_components'][0]);

2 个答案:

答案 0 :(得分:2)

如果您需要获取城市和国家/地区,请尝试此操作

foreach($jsondata['results'] as $r) {
    foreach($r['address_components'] as $n) {
        if($n['types'][0] == "locality" && $n['types'][1] == "political") {
            $city = $n['long_name'];
        }

        if($n['types'][0] == "country" && $n['types'][1] == "political") {
            $country = $n['long_name'];
        }
    }
}

echo $city. ", ". $country. "</br>";

答案 1 :(得分:0)

要获得更准确和直接的结果,您可以显式查询localitycountry的结果。为此,您需要添加参数result_type

使用您的代码,最终结果将是:

$url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' . get_wpgeo_latitude( $post_id ) . ',' . get_wpgeo_longitude( $post_id ) . '&result_type=country|locality&language=de';

这只会在答案中获得countrylocality个实体。更加高效,快速,轻巧和准确。

相关问题