Skip to content

Instantly share code, notes, and snippets.

@m1r0
Last active December 9, 2017 14:56
Show Gist options
  • Save m1r0/8417210 to your computer and use it in GitHub Desktop.
Save m1r0/8417210 to your computer and use it in GitHub Desktop.
PHP-WP: Geocode address to lat and lng
function crb_get_lat_lng_by_address($address) {
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' . urlencode($address) . '&sensor=false';
$transient_key = substr(md5($address), 0, 20);
$coords_cache = get_transient( $transient_key );
if ( $coords_cache !== false ) {
return $coords_cache;
}
$response = wp_remote_get($url);
$xml = @simplexml_load_string($response['body']);
if (strcmp($xml->status, 'OK') == 0) {
$node = $xml->result[0];
foreach ($xml->result as $result) {
// We're looking for a postal code - if there is no postal code, we'll just take the first result...
if ( strtolower($result->type) == 'postal_code' ) {
$node = $result;
break;
}
}
$lat = (float) $node->geometry->location->lat;
$lng = (float) $node->geometry->location->lng;
$coords_cache = array('lat' => $lat, 'lng' => $lng);
set_transient( $transient_key, $coords_cache, 60*60*24 );
return $coords_cache;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment