我正在尝试解析来自谷歌地理编码API的json响应,但我在理解它时遇到了一点麻烦。
对于那些不熟悉地理编码 API 的用户,这里是 URL:http://maps.google.com/maps/api/geocode/json?address=albert%20square&sensor=false
我使用以下代码来解析请求
<?php
$address = urlencode($_POST['address']);
$request = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . $address . "&sensor=false");
$json = json_decode($request, true);
?>
我正在尝试输出以下内容:
echo $json['results'][0]['formated_address'];
我不确定为什么没有回应。我也试过$json[0]['results'][0]['formated_address']
.我知道这是一个菜鸟问题,但多维数组让我感到困惑。
echo $json['results'][0]['formatted_address'];
如果你拼写正确,它会有所帮助;-)
...仅供参考,JSON 请求 URL 必须正确格式化才能返回任何好的东西,否则您可能会得到 NULL 响应。
例如,这是我从 JSON 响应中检索经度和纬度值的方式:
// some address values
$client_address = '123 street';
$client_city = 'Some City';
$client_state = 'Some State';
$client_zip = 'postal code';
// building the JSON URL string for Google API call
$g_address = str_replace(' ', '+', trim($client_address)).",";
$g_city = '+'.str_replace(' ', '+', trim($client_city)).",";
$g_state = '+'.str_replace(' ', '+', trim($client_state));
$g_zip = isset($client_zip)? '+'.str_replace(' ', '', trim($client_zip)) : '';
$g_addr_str = $g_address.$g_city.$g_state.$g_zip;
$url = "http://maps.google.com/maps/api/geocode/json?
address=$g_addr_str&sensor=false";
// Parsing the JSON response from the Google Geocode API to get exact map coordinates:
// latitude , longitude (see the Google doc. for the complete data return here:
// https://developers.google.com/maps/documentation/geocoding/.)
$jsonData = file_get_contents($url);
$data = json_decode($jsonData);
$xlat = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$xlong = $data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
echo $xlat.",".$xlong;
。此外,您可以使用相同的代码对谷歌地图iframe进行硬编码,并将其嵌入到您的页面中,如果V3 API没有行为...请参阅此处的简单教程:http://pmcds.ca/blog/embedding-google-maps-into-the-webpage.html
嵌入并不完全正确的方法,但有时它成为所需的解决方案。