Skip to content

Instantly share code, notes, and snippets.

@bradp
Last active September 5, 2022 20:36
Show Gist options
  • Save bradp/4999343 to your computer and use it in GitHub Desktop.
Save bradp/4999343 to your computer and use it in GitHub Desktop.
WordPress function to convert address to Lat/Long
<?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;
}
@thenumbercreative
Copy link

oh man thanks for this

Copy link

ghost commented May 22, 2014

This is really useful. Thanks so much.

@ShiraStarL
Copy link

WOW tnx!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment