我在php中运行此代码:
$jsonData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=306%20Evarts%20St%20NE%20Washington,%20DC%2020002&key=<hidden>');
$data = json_decode($jsonData, true);
var_dump($data);
具有以下结果(重新格式化为可读):
array(2) {
["results"] => array(1) {
[0] => array(5) {
["address_components"] => array(7) {
[0] => array(3) {
["long_name"] => string(3) "306"
["short_name"]=> string(3) "306"
["types"] => array(1) {
[0]=> string(13) "street_number"
}
}
[1] => array(3) {
["long_name"] => string(23) "Evarts Street Northeast"
["short_name"] => string(12) "Evarts St NE"
["types"] => array(1) {
[0]=> string(5) "route"
}
}
[2] => array(3) {
["long_name"] => string(20) "Northeast Washington"
["short_name"] => string(20) "Northeast Washington"
["types"] => array(2) {
[0] => string(12) "neighborhood"
[1] => string(9) "political"
}
}
[3] => array(3) {
["long_name"] => string(10) "Washington"
["short_name"]=> string(4) "D.C."
["types"]=> array(2) {
[0]=> string(8) "locality"
[1]=> string(9) "political"
}
}
[4]=> array(3) {
["long_name"]=> string(20) "District of Columbia"
["short_name"]=> string(2) "DC"
["types"]=> array(2) {
[0]=> string(27) "administrative_area_level_1"
[1]=> string(9) "political"
}
}
[5]=> array(3) {
["long_name"]=> string(13) "United States"
["short_name"]=> string(2) "US"
["types"]=> array(2) {
[0]=> string(7) "country"
[1]=> string(9) "political"
}
}
[6]=> array(3) {
["long_name"]=> string(5) "20002"
["short_name"]=> string(5) "20002"
["types"]=> array(1) {
[0]=> string(11) "postal_code"
}
}
}
["formatted_address"]=> string(54) "306 Evarts Street Northeast, Washington, DC 20002, USA"
["geometry"]=> array(3) {
["location"]=> array(2) {
["lat"]=> float(38.9248059)
["lng"]=> float(-77.001318)
}
["location_type"]=> string(7) "ROOFTOP"
["viewport"]=> array(2) {
["northeast"]=> array(2) {
["lat"]=> float(38.926154880291)
["lng"]=> float(-76.999969019709)
}
["southwest"]=> array(2) {
["lat"]=> float(38.923456919708)
["lng"]=> float(-77.002666980292)
}
}
}
["place_id"]=> string(27) "ChIJvysMWvjHt4kRjif4nyaEb7U"
["types"]=> array(1) {
[0]=> string(14) "street_address"
}
}
}
["status"]=> string(2) "OK"
}
如何回显结果中的各种值,例如long_name
地址组件?
答案 0 :(得分:0)
您可以使用嵌套的foreach
来循环数组ref:http://php.net/manual/en/control-structures.foreach.php
foreach($data['results'] as $result){
foreach ($result['address_components'] as $value) {
echo $value['long_name'] . '<br>';
}
}
答案 1 :(得分:0)
您可以访问响应数据,如下所示:
$jsonData = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=306%20Evarts%20St%20NE%20Washington,%20DC%2020002&key=API_KEY');
$data = json_decode($jsonData, true);
if($data['status'] == 'OK'){
$latitude = $data['results'][0]['geometry']['location']['lat'];
$longitude = $data['results'][0]['geometry']['location']['lng'];
$formatted_address = $data['results'][0]['formatted_address'];
}