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


Reverse Geocoding: Get city and country

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

这里有两个例子:

德国汉堡

泰国曼谷

我总是需要第一个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实体。更加高效、快速、轻便和准确。