PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Related Articles
Related Books
Beginning Google Maps Applications with PHP and Ajax: From Novice to Professional

Beginning Google Maps Applications with PHP and Ajax: From Novice to Professional

There is much to like about this book. The explanations are straightforward, the code is...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Geocoding with PHP and the Google Maps API

Performing a Geocoder Request

When you perform a geocoder request, you can specify which output type to use. The available options are JSON, XML, KML and CSV. In this article we will be requesting and handling XML data.

Note: KML (which stands for Keyhole Markup Data) is an XML format that was developed for use with Google Earth (formerly called Keyhole). The KML and XML output from the geocoder are identical; however the HTTP mime type that is sent differs for the two types.

Although JSON data is typically used within JavaScript code, we could also easily use this data instead of the XML response. To turn the data into a PHP array you could use the json_decode() function (available since PHP 5.2.0). We will be using SimpleXML in this article to read geocoder data, but to use JSON instead would be a trivial change.

To perform a geocoder request, a HTTP get request is sent to http://maps.google.com/maps/geo. There are three URI parameters that must be specified in this request:

  • q – The address or location that you want to geocoded.
  • key – This is the Google Maps API key that you created earlier in this article.
  • output – This the output format for the response (as discussed above). The values that can be used are json, xml, kml or csv.

For example, if you wanted to find the coordinates of The White House (located at 1600 Pennsylvania Avenue, Washington, DC), you would request the following URL:

Listing 1 Querying the geocoder for a the address of the White House in XML format (listing-1.txt)
http://maps.google.com/maps/geo?q=1600+pennsylvania+ave+washington+dc&output=xml&key=123456
Note: Remember to substitute your own API key in the request URL.

The precise address string you send in the query is not critical – it simply needs enough data in it to identify the location you're after (that is, it should not be ambiguous).

In This Article


Additional Files