Geocode an address with the Google Maps API

This code snippet mini-project, returns a geocode (that is, Latitude and Longitude) from a given address.

Note: This requires that you obtain your own Google Maps API Key and on it’s own violates the Google Maps API Terms and Conditions. In short, you must accompany this with a map, then you’re safe.

It features some basic error handling, which will catch the status messages returned. Unfortunately, this makes the code a little messy, but otherwise you’d have nothing returned.

	$key = "your-key";
	
	/* Given data */
	$street = "My Street";
	$town = "My Town";
	$country = "My Country";
	$postcode = "My Postcode";
	
	$address = urlencode($street . ", " . $town . ", " . $country);

	$xml_input = "http://maps.google.com/maps/geo?q={$address}&output=xml&oe=utf8&sensor=false&key={$key}";
	$xml = simplexml_load_file($xml_input);
	
	$status =  $xml->Response->Status->code; // returned status code
	
	if ($status == "500") {
		echo "Request could not be completed due to a server error. Please try again.";
	} 
	if ($status == "601") {
		echo "You didn't pass an address. Please try again.";
	}
	if ($status == "602") {
		echo "The address could not be found. Please try again.";
	}
	if ($status == "603") {
		echo "The address cannot be returned due to legal or contractual reasons.";
	}
	if ($status == "610") {
		echo "The API key used is invalid or doesn't match the domain.";
	}
	if ($status == "620") {
		echo "Too many requests have been sent. You've either reached the limit, or sent too many at once.";
	}
	else {
		echo "<h2>Coordinates";
		$coords = $xml->Response->Placemark->Point->coordinates; // return coords
		// splits and reverses the returned string to make it correct
		$latlong = explode(",", $coords);
		echo $latlong[1] . ", " . $latlong[0];
	}

This returns the latitude and longitude of the address passed to it, for example: 51.2343500, -0.7325510. You can also access this through the $latlong array.

Naturally, it’s had my details stripped out of it. You can get an API key here.

Read more: http://code.google.com/apis/maps/documentation/geocoding/index.html

Posted at 9:44 on 5 th July 2009