【问题标题】:Using Google geocode API with full address to return several values from JSON使用带有完整地址的 Google 地理编码 API 从 JSON 返回多个值
【发布时间】:2017-08-30 17:34:30
【问题描述】:

我收到了

的输出
http://maps.google.com/maps/api/geocode/json?address={$address}

JSON 格式。然后像这样拉出经纬度

$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];

所有这些都很好。但我还需要此处包含的县名

...
"results" : [
      {
         "address_components" : [
            {
               "long_name" : "Platte City",
               "short_name" : "Platte City",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Carroll Township",
               "short_name" : "Carroll Township",
               "types" : [ "administrative_area_level_3", "political" ]
            },
            {
               "long_name" : "Platte County",
               "short_name" : "Platte County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Missouri",
               "short_name" : "MO",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "64079",
               "short_name" : "64079",
               "types" : [ "postal_code" ]
            }
         ],
...

我试过了

for ($i = 0; $i < 10; $i++) {
$type2 = $resp['results'][0]['address_components'][$i]['types'];
if (stripos(strtolower($type2), 'administrative_area_level_2') !== false){

    $county = $resp['results'][0]['address_components'][$i]['long_name'];

                } else {$county = "$i Unknown County";}
        }

如您所见,县位于“administrative_area_level_2”,但尝试了几个小时后,我得到的只是“未知县”。 Google API 声明它不会总是在 XML/JSON 中的相同位置,这似乎是正确的。有时它在位置 3 有时在 5 有时在其他位置。 谁能给我一个如何获得县名的例子。

【问题讨论】:

    标签: json google-geocoder


    【解决方案1】:
        // Routine to find the County name
          foreach ($resp['results'][0]['address_components'] as $comp) {
            //loop through each component in ['address_components']     
            foreach ($comp['types'] as $currType){          
           //for every type in the current component, check if it = the check
    
            if($currType == 'administrative_area_level_2'){
                //echo $comp['long_name'];
                    $county = $comp['long_name'];
                        }           }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-25
      • 2014-05-18
      • 1970-01-01
      • 2010-12-24
      • 2013-06-14
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多