Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Last active March 5, 2019 15:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisveness/c8b2a90bcfa91aa1e919 to your computer and use it in GitHub Desktop.
Save chrisveness/c8b2a90bcfa91aa1e919 to your computer and use it in GitHub Desktop.
Geocode an address using Google API
<?php
/**
* 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 developers.google.com/maps/documentation/geocoding
$locn = (object)array('lat'=>null, 'lon'=>null, 'status'=>null, 'address'=>null);
$url = 'http://maps.googleapis.com/maps/api/geocode/json';
$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