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

Creating the Point Class

The final class we need to implement to make use of our geocoder is the Point class. This class is to hold a single latitude and longitude value. These values are set by passing them in the class constructor, and retrieved by calling the getLatitude() and getLongitude() methods respectively.

The other method we will implement in this class is a static factory method called Create(), which is called by the Placemark class.

The code for this class should reside in a file called Point.php. The complete file is available from the article file downloads section.

We begin the Point class in Listing 16, by creating properties for the latitude and longitude, as well as implementing the constructor, used to set these values.

Listing 16 Initializing the Point class (listing-16.php)
<?php
    class Point
    {
        protected $_lat;
        protected $_lng;
 
        public function __construct($latitude, $longitude)
        {
            $this->_lat = $latitude;
            $this->_lng = $longitude;
        }
 
        // other code
    }
?>

Next we implement the methods used to retrieve the longitude and latitude values, as shown in Listing 17.

Listing 17 The getLatitude() and getLongitude() methods (listing-17.php)
<?php
    class Point
    {
        // other code
 
        public function getLatitude()
        {
            return $this->_lat;
        }
 
        public function getLongitude()
        {
            return $this->_lng;
        }
 
        // other code
    }
?>

Finally, we implement the Create() factory method. This static method accepts a string in the format we receive it from the geocoder (that is, latitude,longitude,elevation). To create the new Point object we simply split this string on the comma character and instantiate Point with the values, as shown in Listing 18.

Listing 18 Implementing the Create() factory method (listing-18.php)
<?php
    class Point
    {
        // other code
 
        public static function Create($str)
        {
            list($longitude, $latitude, $elevation) = explode(',', $str, 3);
 
            return new self($latitude, $longitude);
        }
    }
?>

This concludes the three classes that make up our geocoder, meaning we now use the geocoder as required. In the next section we will implement a simple web-based interface to the geocoder.

In This Article


Additional Files