首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用PHP解析Google Geocoding JSON

用PHP解析Google Geocoding JSON
EN

Stack Overflow用户
提问于 2012-05-24 18:28:10
回答 2查看 21.4K关注 0票数 16

我正在尝试解析来自Google Geocode API的json响应,但我在理解它时遇到了一些问题。

对于那些不熟悉地理编码应用编程接口的用户,这里提供了以下网址:http://maps.google.com/maps/api/geocode/json?address=albert%20square&sensor=false

我使用以下代码来解析请求

代码语言:javascript
复制
<?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);

?>

我正在尝试输出以下内容:

代码语言:javascript
复制
echo $json['results'][0]['formated_address'];

我不确定为什么什么都没有得到回应。我也尝试过$json[0]['results'][0]['formated_address']。我知道这是一个新手问题,但是多维数组让我感到困惑。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-24 18:31:48

代码语言:javascript
复制
echo $json['results'][0]['formatted_address'];

如果拼写正确,会有所帮助;-)

票数 15
EN

Stack Overflow用户

发布于 2013-05-09 05:15:38

JSON请求URL必须正确格式化才能返回任何好的内容,否则可能会得到...just响应。

例如,下面是我从响应中检索JSON经度和纬度JSON值的方法:

代码语言:javascript
复制
// 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;

如果v3 ...also不工作,您可以使用相同的代码对Google Map iframe进行硬编码,并将其嵌入到您的页面中。在这里查看简单的教程:http://pmcds.ca/blog/embedding-google-maps-into-the-webpage.html

嵌入并不完全是正确的方法,,但有时需要它来解决问题。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10735662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档