web-dev-qa-db-ja.com

PHP)を使用してGoogleジオコーディングJSONを解析する

Google Geocode APIからのjson応答を解析しようとしていますが、理解するのに少し問題があります。

Geocode 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']。私はこれが初心者の質問であることを知っていますが、多次元配列は私を混乱させます。

15
Lee Price
echo $json['results'][0]['formatted_address'];

あなたがそれを正しくつづればそれは役に立ちます;-)

14
DaveRandom

...参考までに、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;

...また、同じコードを使用してGoogle Map iframeをハードコーディングし、v3 APIが動作しない場合はページに埋め込むことができます...こちらの簡単なチュートリアルを参照してください: http:// pmcds。 ca/blog/embedding-google-maps-into-the-webpage.html

を埋め込むことは、正確に正しいアプローチではありませんが、必要な解決策になる場合があります。

8
Milan