Created
May 10, 2014 16:11
-
-
Save dongilbert/f82ac613f2f4252d2bc1 to your computer and use it in GitHub Desktop.
Geocode an address, passed as array params
This file contains hidden or 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 | |
/** | |
* Geocode an address. | |
* | |
* @param mixed $params Array containing address info or string address. | |
* | |
* @return array Array of longitude or latitude data. | |
*/ | |
function getLatLng($params) | |
{ | |
static $locations = array(); | |
$store = md5(json_encode($params)); | |
if (!isset($locations[$store])) | |
{ | |
if (is_object($params)) | |
{ | |
$params = get_object_vars($params); | |
} | |
if (is_array($params)) | |
{ | |
$tmp = array(); | |
$tmp[] = (isset($params['address1'])) ? $params['address1'] : $params['address']; | |
$tmp[] = $params['city']; | |
$tmp[] = $params['state']; | |
$tmp[] = $params['zip']; | |
$address = implode(',', $tmp); | |
} | |
else | |
{ | |
$address = $params; | |
} | |
$address = urlencode($address); | |
$geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address={$address}&sensor=false"); | |
$output = json_decode($geocode); | |
if ($geocode === false || $output === null || $output->status == 'ZERO_RESULTS') | |
{ | |
$lat = 0; | |
$lng = 0; | |
} | |
else | |
{ | |
$lat = $output->results[0]->geometry->location->lat; | |
$lng = $output->results[0]->geometry->location->lng; | |
} | |
$locations[$store] = array('latitude' => $lat, 'longitude' => $lng); | |
} | |
return $locations[$store]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment