The way I am doing it is by making two calls.
On the first call my query is: geocode('address=' .$cty. ',' .$st, $key);
$cty = city name - $st = state abbreviation - $key is my api key
-
On the second call my query is: geocode('latlng=' .$lat. "," .$lng, $key);
$lat = latitude from first call - $lng = longitude from first call
---------
My function appears below.
--------------------------------------
function geocode($query, $key){
global $lat, $lng, $zipcode, $city, $state;
$url = 'https://maps.googleapis.com/maps/api/geocode/json?'.$query.'&key='.$key;
$json_string = curlfun($url); // this uses CURL to access the url (false on fail)
if($json_string){
$parsed_json = json_decode($json_string, true);
//
if ($parsed_json['status'] == "OK"){
$lat = $parsed_json['results'] [0] ['geometry'] ['location'] ['lat'];
$lng = $parsed_json['results'] [0] ['geometry'] ['location'] ['lng'];
foreach($parsed_json['results'] [0] ['address_components'] as $a){
if($a ['types'] [0] == 'postal_code') $zipcode = $a ['long_name'];
if($a ['types'] [0] == 'locality') $city = $a ['long_name'];
if($a ['types'] [0] == 'administrative_area_level_1') $state = $a ['short_name'];
}
}
else return false;
}
else return false;
if(!$city) return false; // if there is no city just return false.
return true;
}
---------------------------------------------------
The global variables are available to the rest of the script after the function call. The function returns false on failure or true on success. Appropriate error handling should be done in the main code.