Skip to content

Instantly share code, notes, and snippets.

@tormjens
Created May 7, 2014 10:41
Show Gist options
  • Save tormjens/1dac66ba98903e474047 to your computer and use it in GitHub Desktop.
Save tormjens/1dac66ba98903e474047 to your computer and use it in GitHub Desktop.
Get the name of the administrative place based on latitude and longitude from the Google Maps API. Includes transient caching and use of wp_remote_get-function.
function get_administrative_name($lat, $lng, $level = 'administrative_area_level_2', $expire = null) {
if(!$expire)
$expire = 60 * 60 * 24 * 7 * 4; // keep for a month
$transient = 'cached_administrative_name_'. str_replace('.' , '', $lat) .''. str_replace('.' , '', $lng);
if( false === ($place = get_transient( $transient ) ) ) {
$city = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false';
$json = wp_remote_get( $city );
$json = json_decode($json['body']);
$json = $json->results[0]->address_components;
foreach($json as $address) {
if($address->types[0] == $level)
$place = $address->long_name;
}
set_transient( $transient, $place );
}
return $place;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment