php – 使用谷歌反向地理编码获取街道,城市和国家

前端之家收集整理的这篇文章主要介绍了php – 使用谷歌反向地理编码获取街道,城市和国家前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从google json获取$street,$city和$country字符串.
它适用于我的家庭住址:
http://maps.googleapis.com/maps/api/geocode/json?latlng=52.108662,6.307370&sensor=true
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
    $data = @file_get_contents($url);
    $jsondata = json_decode($data,true);
    if(is_array($jsondata) && $jsondata['status'] == "OK")
    {
          $city = $jsondata['results']['0']['address_components']['2']['long_name'];
          $country = $jsondata['results']['0']['address_components']['5']['long_name'];
          $street = $jsondata['results']['0']['address_components']['1']['long_name'];
    }

但是对于一个不同的地址,数组中有更多的数据就像这个例子:
http://maps.googleapis.com/maps/api/geocode/json?latlng=52.154184,6.199592&sensor=true
它不起作用,因为在json数组中有更多的数据,并且使省份成为该国.

如何选择我需要的类型(long_name)?

> for street:long_name其中“types”:[“route”]
> for city:long_name where“types”:[“locality”,“political”]
>国家:long_name哪里“types”:[“国家”,“政治”]

地理编码JSON的输出示例:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "89","short_name" : "89","types" : [ "street_number" ]
            },{
               "long_name" : "Wieck De","short_name" : "Wieck De","types" : [ "establishment" ]
            },{
               "long_name" : "Industrieweg","short_name" : "Industrieweg","types" : [ "route" ]
            },{
               "long_name" : "Zutphen","short_name" : "Zutphen","types" : [ "locality","political" ]
            },"types" : [ "administrative_area_level_2",{
               "long_name" : "Gelderland","short_name" : "GE","types" : [ "administrative_area_level_1",{
               "long_name" : "Nederland","short_name" : "NL","types" : [ "country",{
               "long_name" : "7202 CA","short_name" : "7202 CA","types" : [ "postal_code" ]
            }

我想我自己修改了,特此我的代码

// street
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("route",$address["types"])) {
            $street = $address["long_name"];
        }
    }
}
// city
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("locality",$address["types"])) {
            $city = $address["long_name"];
        }
    }
}
// country
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("country",$address["types"])) {
            $country = $address["long_name"];
        }
    }
}
您可以将数据转换为关联数组,并使用它
$data = array();
 foreach($jsondata['results']['0']['address_components'] as $element){
     $data[ implode(' ',$element['types']) ] = $element['long_name'];
 }
 print_r($data);

 echo 'route: ' . $data['route'] . "\n";
 echo 'country: ' . $data['country political'];

猜你在找的PHP相关文章