Geocode an address using Google API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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