Back to blog

PHP Geocoding function, from address to coordinates lat long

This is a small function included in the Minibots Class that converts an address to a couple of coordinates Latitude,…

This is a small function included in the Minibots Class that converts an address to a couple of coordinates Latitude, Longitude that can be used to place a marker on a map.
This function uses Google’s geocoding service called with the file_get_contents function (CURL not needed).
The result is decoded with a preg_match call that searches for the center data of the map returned.
You can test the function with this online demo.

// ------------------------------------------
// converts a string with a stret address
// into a couple of lat, long coordinates.
// ------------------------------------------
public function getLatLong($address){
	if (!is_string($address))die("All Addresses must be passed as a string");
	$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
	$_result = false;
	if($_result = file_get_contents($_url)) {
		if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
		preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
		$_coords['lat'] = $_match[1];
		$_coords['long'] = $_match[2];
	}
	return $_coords;
}

Canonical URL