Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Created May 4, 2012 23:05
Show Gist options
  • Save pdewouters/2598246 to your computer and use it in GitHub Desktop.
Save pdewouters/2598246 to your computer and use it in GitHub Desktop.
geocode an address in php
// Geocodes an address and returns an array with long / lat
function do_geocode_address( $address ){
// Send GET request to Google Maps API
$api_url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=';
$api_response = wp_remote_get( $api_url . urlencode( $address ) );
//Get the JSON object
$json = wp_remote_retrieve_body ( $api_response );
// make sure request was successful or return false
if( empty( $json ) )
return false;
// decode the JSON object
// return an array with lat / long
$json = json_decode( $json );
$lat_long = array(
'latitude' => $json->results[0]->geometry->location->lat,
'longitude' => $json->results[0]->geometry->location->lng
);
return $lat_long;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment