Get latitude and longitude from postcode

Posted on: September 12th, 2013 by admin No Comments

Great little function to fetch the latitude and longitude from any postcode using the Google Maps API:

1
2
3
4
5
6
7
8
9
10
11
function _get_lat_lng($address) {
	$address = str_replace(' ','',$address);
	$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$address.'&sensor=false';
	$output = json_decode(file_get_contents($url));
	if(isset($output->results) && is_array($output->results) && isset($output->results[0]->geometry->location)){
		$lat = $output->results[0]->geometry->location->lat;
		$long = $output->results[0]->geometry->location->lng;
		if($lat && $long) return "$lat, $long";
	}
	return false;
}