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

Reverse Geocoding: Get city and country

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

这里有两个例子:

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

如果你需要获取城市和国家,试试这个

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

要获得更准确和直接的结果,您可以显式查询 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 个实体。更加高效、快速、轻便和准确。