Vojta
Vojta

Reputation: 379

Google API multidimensional array

I´m bit stuck. Why am I not pulling out latitude and longitude in my code? I can´t see the flaw. Thank you in advance!

$json  = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=Boston');
$result = json_decode($json, true);

$glat = $result->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$glong = $result->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

print $glat.",".$glong;

Upvotes: 0

Views: 57

Answers (1)

Jan-Willem de Boer
Jan-Willem de Boer

Reputation: 797

You are using the results as an object but it is an array, here is the fixed code:

    $json  = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=Boston');
    $result = json_decode($json, true);

    $glat = $result['results'][0]['geometry']['location']['lat'];
    $glong = $result['results'][0]['geometry']['location']['lng'];

Upvotes: 1

Related Questions