Skip to content

Instantly share code, notes, and snippets.

@aaronranard
Forked from bradp/gist:4999343
Created July 23, 2013 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronranard/6063163 to your computer and use it in GitHub Desktop.
Save aaronranard/6063163 to your computer and use it in GitHub Desktop.
WordPress: Address to Latitude / Longitude
<?php
function brrad_geocode($street_address,$city,$state){
$street_address = str_replace(" ", "+", $street_address); //google doesn't like spaces in urls, but who does?
$city = str_replace(" ", "+", $city);
$state = str_replace(" ", "+", $state);
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$street_address,+$city,+$state&sensor=false";
$google_api_response = wp_remote_get( $url );
$results = json_decode( $google_api_response['body'] ); //grab our results from Google
$results = (array) $results; //cast them to an array
$status = $results["status"]; //easily use our status
$location_all_fields = (array) $results["results"][0];
$location_geometry = (array) $location_all_fields["geometry"];
$location_lat_long = (array) $location_geometry["location"];
echo "<!-- GEOCODE RESPONSE " ;
var_dump( $location_lat_long );
echo " -->";
if( $status == 'OK'){
$latitude = $location_lat_long["lat"];
$longitude = $location_lat_long["lng"];
}else{
$latitude = '';
$longitude = '';
}
$return = array(
'latitude' => $latitude,
'longitude' => $longitude
);
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment