Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Geocode an address using Google API
* Geocodes an address using Google API (limit 2500/day).
* @param string $address - Address to be geocoded.
* @param string [$region=gb] - Region results are to biased to.
* @return object {lat, lon, status, address}.
function geocode($address, $region='gb')
// qv
$locn = (object)array('lat'=>null, 'lon'=>null, 'status'=>null, 'address'=>null);
$url = '';
$arg = array('address'=>$address, 'region'=>$region);
$qry = http_build_query($arg);
$json = json_decode(file_get_contents($url.'?'.$qry));
if ($json->status != 'OK') {
$locn->status = $json->status;
return $locn;
$locn->status = 'OK';
$locn->lat = $json->results[0]->geometry->location->lat;
$locn->lon = $json->results[0]->geometry->location->lng;
$locn->address = $json->results[0]->formatted_address;
return $locn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment