我想让州和县从一个地址使用地理代码与谷歌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;
latitude
、longitude
和formatted_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"
}
最佳答案
根据您显示的json
数据,您需要获得如下state
和county
:
$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;
关于php - 从地址获取州和县,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35248226/