Get Timezone by Latitude and Longitude in PHP

I was going through a bunch of GPS data on a project recently and needed to know the local times of the files – a task that's impossible without knowing the local time zones. After a bit of research, I found that the folks over at GeoNames had created an awesome (and free!) web service that allows you to look up a time zone of a given point by latitude and longitude. Using PHP's built in cURL library and SimpleXML extension, I put together a function that goes straight from latitude and longitude to timezone. Here is that function:


function get_timezone($latitude,$longitude,$username) {

	//error checking
	if (!is_numeric($latitude)) { custom_die('A numeric latitude is required.'); }
	if (!is_numeric($longitude)) { custom_die('A numeric longitude is required.'); }
	if (!$username) { custom_die('A GeoNames user account is required. You can get one here:'); }

	//connect to web service
	$url = ''.$latitude.'&lng='.$longitude.'&style=full&username='.urlencode($username);
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$xml = curl_exec($ch);
	if (!$xml) { $GLOBALS['error'] = 'The GeoNames service did not return any data: '.$url; return false; }

	//parse XML response
	$data = new SimpleXMLElement($xml);
	//echo '<pre>'.print_r($data,true).'</pre>'; die();
	$timezone = trim(strip_tags($data->timezone->timezoneId));
	if ($timezone) { return $timezone; }
	else { $GLOBALS['error'] = 'The GeoNames service did not return a time zone: '.$url; return false; }



And, here's a quick example of the function in action (you'd need to replace demo with your own GeoNames account):

$timezone = get_timezone(-33.8578101,151.2138672,'demo');
echo $timezone;
//returns "Australia/Sydney"

And, of course, you could take this a step further and go from city to time zone, or postal address to time zone, by looking up the latitude and longitude via Google's Geocoding API.



This post was published on December 24th, 2014 by Robert James Reese in the following categories: cURL, Maps, and PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.