Google Maps Geocoding API for PHP

Google Maps Geocoding APIToday I have been exploring the Geocoding function of the Google Maps API (v.3). I had never before dealt with JSON so I had some studying to do to make sense of the output. It isn’t rocket science, but it kept me busy for a while to turn it into usable data.

As I’m sure more people will be running into similar challenges when working with the geocoding API, I thought I’d share my code. It’s basically a small function that dumps the important data from the JSON into an nicely readable associative array. As the Google Maps API returns 2 sets of data, one with the address details and the other with status information, the function first checks to see if the status returned OK and if that’s the case, coordinates as well as address details are put into an array.

Simply run the function on your address to retrieve the details:


geocode("1600 Amphitheatre Parkway, Mountain View, CA");

This should return an array with the following information:

Array
(
    [lat] => 37.4226007
    [lng] => -122.0852857
    [street_number] => 1600
    [route] => Amphitheatre Parkway
    [locality] => Mountain View
    [administrative_area_level_2] => Santa Clara
    [administrative_area_level_1] => California
    [country] => United States
    [postal_code] => 94043
)

It’s that simple. Just copy and paste the following function into your code and that’s it.


function geocode($address) {
	$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . str_replace(" ", "+", $address) . "&sensor=false";
	$json = json_decode( file_get_contents($url) );
	if($json->status == "OK") {
		$fullarray = $json->results[0];

		$geo["lat"] = $fullarray->geometry->location->lat;
		$geo["lng"] = $fullarray->geometry->location->lng;

		$components = $fullarray->address_components;

		foreach($components as $component) {
			$type = $component->types[0];
			$value = $component->long_name;
			$geo[$type] = $value;
		}

		return $geo;

	} else {

		return die("Unable to connect to retrieve details for $address");

	}
}

Next step is to display the data on a map so I might write a short article on that as well if there’s interest.

1 Comment