【问题标题】:Reverse Geocoding: Get city and country反向地理编码:获取城市和国家
【发布时间】:2015-11-03 19:44:44
【问题描述】:

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

这里有两个例子:

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

【问题讨论】:

    标签: php reverse-geocoding


    【解决方案1】:

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

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

    【讨论】:

    • 当循环没有进入if条件时会发生什么?如何处理else
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 2015-03-03
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多