I get this PHP Notice: Undefined offset: 0 on line 9 (line 9 is highlighted in bold within the code I have provided). It is regarding the Google Geocode API in the code provided below.
An undefined offset error occurs when you try to reference an array value at position 0 but that position doesn't exist. I am assuming the Google geocode API has changed within the last year. As it must be returning a different result structure then the one originally programmed with. However, although I know this, I cannot find anything wrong with the code. Does anyone know if the format of my code is incorrect?
I have looked at the Google Geocode API documentation. It says it must be laid out like this:
https://maps.googleapis.com/maps/api/geocode/outputFormat?parameters
However, my code is more complicated then that. I was wondering if there is an issue with the order or syntax of my parameters. I am just not experienced enough to work this one out myself, which is why I would really appreciate some help on this.
The code below pulls the country and town fields from an input form. The Google Geocode works out the lat and lng of the town, then feeds this to the timezone API to calculate the timezone. I have hidden my API key for security purposes. Any help is appreciated. Thank you.
<?php $town = urldecode($_GET['town']); $country = urldecode($_GET['country']); if(!empty($_GET['state'])){ $state = urldecode($_GET['state']); }
$location = json_decode(@file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?key=API_KEY_HERE&address='.urlencode($town.', '.(!empty($state) ? $state.', ' : '').$country)), true)['results'][0]['geometry']['location'];
$timezone = json_decode(@file_get_contents('https://maps.googleapis.com/maps/api/timezone/json?key=API_KEY_HERE&location='.$location['lat'].','.$location['lng'].'×tamp='.date('U')), true); $time = $timezone['rawOffset'] / 60 / 60; echo $time; ?>