TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

CakePHP geocoding behavior

CakePHP Geocoding behavior is a CakePHP behavior which helps finding lat and lng in Google Map from a given zipcode or address. Before you start reading, make sure you have good understanding of CakePHP behavior, and at least have experience using CakePHP behavior. If not, we recommend you to read Cook Book behavior first. In this tutorial we will introduce you Geocoding behavior as well as demonstrate a simple example.

Geocoding behavior

  • Geocoding behavior is a CakePHP behavior which helps finding lat and lng in Google Map from a given zipcode/address, you can download the behavior here.
  • Geocoding behavior is retrieving data from Google geocoding services (http://maps.google.com/maps/api/geocode), and it is using json data type.

Preparation

How to use

  • Create a database table called "places" to store lat and lng:
CREATE TABLE `places` (
  `id` int(11) NOT NULL auto_increment,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 
COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;

Note: We have defined float(10,6) to store both lat and lng.

  • Place your downloaded geocoding.php into "app/models/behaviors/geocoding.php".

  • Create your place model "app/models/place.php" and include Geocoding behavior:

<?php 
class Place extends AppModel {
    public $actsAs = array('Geocoding');
}
?>

If you don't supply any parameters to this behavior, it will try to geocode lat and lng from $this->data['Place']['address'].

  • Now if you call $this->Place->save($data) from anywhere, it will geocode lat and lng from $data['Place']['address'] and store retrieved data to database table's lat and lng attributes.

Customization

  • There are three pamameters you can config while using Geocoding behavior as below:
public $actsAs =
 array('Geocoding'=>
    	array(
            'address'=>'',
            'lat_field'=>'',
            'lng_field'=>''
            )
      );
  1. Set value of "address" to customize the field to do geocoding from, by default, its value is "address".
  2. Set value of "lat_field" to customize the database table's lat attribute for storing data, by default, its value is "lat".
  3. Set value of "lng_field" to customize the database table's lng attribute for storing data, by default, its value is "lng".

The End

If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.