PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
Related Articles

Geocoding with PHP and the Google Maps API

Using the Geocoder

Now that the Geocoder, Placemark and Point class are complete, we can make use of our geocoding implementation. To do so, we will now create a simple web-based interface to the geocoder. This script will display a form with a single text input, which allows the user to enter their desired location to find coordinates for. When they submit the form, the request will be sent to Google and the results will be displayed to the user.

The code for this script can be written to any file you like, but I have called it index.php for the sake of this article. The full script is available from the article file downloads section.

This code works by displaying a form that submits back to itself. At the start of the class we check if the address value has been submitted, and if so a geocoder request is performed.

Listing 19 shows the beginning of the index.php file, which first checks the $_GET variable for a submitted address. If there is a value, the Geocoder class is instantiated and a request is performed. I have also included some basic exception handling. That is, if an error occurs (such as invalid key being specified), the code is displayed and the script exits.

Listing 19 Checking for a submitted address and performing a geocoder request accordingly (listing-19.php)
<?php
    if (isset($_GET['address']))
        $address = $_GET['address'];
    else
        $address = '';
 
    $lookupPerformed = false;
 
    if (strlen($address) > 0) {
        require_once('Geocoder.php');
        $geocoder = new Geocoder('your key here');
 
        try {
            $placemarks = $geocoder->lookup($address);
        }
        catch (Exception $ex) {
            echo $ex->getMessage();
            exit;
        }
 
        $lookupPerformed = true;
    }
?>
Note: Once again, remember to substitute in your own Google Maps API key. Also remember that you don't have to hard-code this value; it may be stored in another script, an external file or in a database.

Next we include the HTML output in the index.php script, as shown in Listing 20. At the top of the page we show the form, which consists of a text input and a submit button. If a request has been submitted we re-display that value in the text input.

Listing 20 Displaying the geocoder input form (listing-20.php)
<html>
    <head>
        <title>Google Geocoder</title>
    </head>
    <body>
        <div>
            <form method="get" action="index.php">
                <div>
                    <input type="text" 
                           name="address" 
                           value="<?php echo htmlSpecialChars($address) ?>" />
                    <input type="submit" value="Lookup" />
                </div>
            </form>
Note: Remember to escape the user-submitted variable $address using htmlSpecialChars() to prevent malicious code from being executed (or to prevent characters being displayed that will break the HTML output, such as ").

Next we check if a geocoder request has been performed (using the $lookupPerformed variable created in Listing 19), and if so, we output the results from the request. Listing 21 shows the code used to do this, which outputs each returned placemark with its formatted and its coordinates.

Listing 21 The HTML code used to display each found placemark (listing-21.php)
<?php if ($lookupPerformed) { ?>
                <hr />
 
                <h2>Geocoder Results</h2>
 
                <?php if (count($placemarks) > 0) { ?>
                    <dl>
                        <?php foreach ($placemarks as $placemark) { ?>
                            <dt><?php echo htmlSpecialChars($placemark) ?></dt>
                            <dd>
                                Latitude <?php echo $placemark->getPoint()->getLatitude() ?>,
                                Longitude <?php echo $placemark->getPoint()->getLongitude() ?>
                            </dd>
                        <?php } ?>
                    </dl>
                <?php } else { ?>
                    <p>
                        No matches found for <strong><?php echo htmlSpecialChars($address) ?></strong>
                    </p>
                <?php } ?>
            <?php } ?>
        </div>
    </body>
</html>

This now concludes the code required to use the geocoder. In Figure 1, I have shown the output when querying main st, usa. This is an ambiguous location that results in many matches from the geocoder.

Figure 1 Sample output when multiple placemarks are found
Figure 1: Sample output when multiple placemarks are found

In This Article


Additional Files