2016-02-07 39 views
3

我想通过使用地理编码和Google API从地址获得州和县。这是我的代码:从地址获取州和县

$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$street.''.$plz.''.$city.'&sensor=false'); 
     $output= json_decode($geocode); 
     $lat = $output->results[0]->geometry->location->lat; 
     $long = $output->results[0]->geometry->location->lng; 
     $formatted_adress = $output->results[0]->formatted_address; 
     $state = $output->results[0]->address_components->administrative_area_level_2; 
     $county = $output->results[0]->address_components->administrative_area_level_1; 

latitudelongitudeformatted_adress作品找到,我可以将结果保存到我的数据库,但州和县不起作用。

这是输出:

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "Hauptgasse", 
       "short_name" : "Hauptgasse", 
       "types" : [ "route" ] 
      }, 
      { 
       "long_name" : "Solothurn", 
       "short_name" : "Solothurn", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "Solothurn", 
       "short_name" : "Solothurn", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "Solothurn", 
       "short_name" : "Südost", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "Schweiz", 
       "short_name" : "CH", 
       "types" : [ "country", "political" ] 
      }, 
      { 
       "long_name" : "4500", 
       "short_name" : "4500", 
       "types" : [ "postal_code" ] 
      } 
     ], 
     "formatted_address" : "Hauptgasse, 4500 Solothurn, Schweiz", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 47.2088079, 
        "lng" : 7.540025399999999 
       }, 
       "southwest" : { 
        "lat" : 47.2065432, 
        "lng" : 7.535295899999999 
       } 
      }, 
      "location" : { 
       "lat" : 47.20778, 
       "lng" : 7.537360000000001 
      }, 
      "location_type" : "GEOMETRIC_CENTER", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 47.20902453029149, 
        "lng" : 7.540025399999999 
       }, 
       "southwest" : { 
        "lat" : 47.20632656970849, 
        "lng" : 7.535295899999999 
       } 
      } 
     }, 
     "partial_match" : true, 
     "place_id" : "ChIJS4BfGfnXkUcRqLUKnJzN54U", 
     "types" : [ "route" ] 
     } 
    ], 
    "status" : "OK" 
} 
+1

通过打印出来给我们显示'$ output'然后只有我们可以建议你需要做什么? –

回答

1

根据表现出你需要得到statecounty像下面您json数据: -

$state = $output->results[0]->address_components[2]->long_name;// i assume `Solothurn` is state name 
$county = $output->results[0]->address_components[4]->long_name; // i assume `Schweiz` is county name 

如果县名也Solothurn然后就改变县代码如下: -

$county = $output->results[0]->address_components[3]->long_name; 
+0

谢谢。 schweiz是英文瑞士的国名 –

+0

感谢哥们,很高兴帮助你 –

+0

还有另外一个问题看我的答案 –