Google Geocoding API with PHP

If you want to know where a particular address is by latitude and longitude, but only have the normal address details like street, city, zip, country, etc. then the Google Geocoding API should be able to help. By passing it an address string it will try to work out (just like Google Maps) whereabouts the address is, and return you a JSON or XML response with what it managed to figure out.

Below is a basic PHP example using cURL (based on an example from Stack Overflow by Jack W)

<pre>
<?php

function lookup($string){

   $string = str_replace (" ", "+", urlencode($string));
   $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $details_url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $response = json_decode(curl_exec($ch), true);

   // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
   if ($response['status'] != 'OK') {
   	return null;
   }

   print_r($response);
   $geometry = $response['results'][0]['geometry'];

	$longitude = $geometry['location']['lat'];
	$latitude = $geometry['location']['lng'];

	$array = array(
		'latitude' => $geometry['location']['lng'],
		'longitude' => $geometry['location']['lat'],
		'location_type' => $geometry['location_type'],
	);

	return $array;

}

$city = 'San Francisco, USA';

$array = lookup($city);
print_r($array);

?>
</pre>

6 Comments

  • $array = array(
    ‘latitude’ => $geometry['location']['lng'],
    ‘longitude’ => $geometry['location']['lat'],
    ‘location_type’ => $geometry['location_type'],
    );

    I think you need to reverse the longitude and latitude assignments in the array.

    Otherwise, great work!!!

    • Haha I didn’t even notice that, which is odd as I must’ve fixed it in the production code I used it in! Thanks

    • Good catch! And, Andrew, thank you! This is so great.

  • [...] location. GPS coordinates were extracted from Google, using the following php file, inspired by http://www.andrew-kirkpatrick.com/ on Google geocoding api with php webpage. Population was interpolated from INSEE’s datasets, [...]

  • Thank you for this piece of code! I planned to use it for a project, but since Google wants to force me to use the data from its Geocoding API in a Google Map, I had to change my plans. That’s too restrictive.

  • This is really useful.

    Btw, besides the above statement, also this one:
    $longitude = $geometry['location']['lat'];
    $latitude = $geometry['location']['lng'];
    can be removed. :)

    Thanks for posting this, make it easy for me.

Leave a comment

Twitter