Skip to content

Instantly share code, notes, and snippets.

@huubl
Forked from bradp/gist:4999343
Created September 5, 2022 20:36
Show Gist options
  • Save huubl/5f4c81d133380489228f3d778a4a2fca to your computer and use it in GitHub Desktop.
Save huubl/5f4c81d133380489228f3d778a4a2fca 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment