Geocoding with CakePHP

Geocoding is a very powerful tool if you want to work with lat/lng, distances or just want to display a small map for your addresses. I use it in combination with my GoogleMaps Helper to display a dynamic or a static map with those addresses (as small pins on the map) or to display how far away you currently are (in km or miles) from this point.

The full package consists of a Lib, a Behavior and their tests and is in my Tools plugin.

Basics first: The lib

I moved the actual querying to a lib for flexibility and better unit testing. It can be used standalone from anywhere in your app where you want to geocode an address (get lat/lng) or reverse-geocode coordinates etc.

Distance

Convert

$result = $this->Geocode->convert($value, $fromUnit, $toUnit);

helps to convert miles to km etc.

Blur

$coordinate = GeocodeLib::blur($coordinate, $level); // level=1...5

Helpful when saving geocoded user data and displaying them publicly (google map etc).
It would be dangerous to display the exact coordinates (if they entered their street name and number) of other users. In such a case you should modify the coordinates prior to displaying them. The above code snippet can be used in the view before you pass it on to the GoogleMap helper or before you print it out. The higher the level the more blurred the coordinate.

The Behavior for (automatic) geocoding on the fly

So if we have an address model, all we need to do is adding three fields: lat, lng (both float 9,4 for example) and formatted_address (optional if you want to capture/store the full address string).
Those will be filled by the behavior if we attach our behavior like so:

Override means it always updates the coordinates if the address is provided. Real means the fields have to actually exist in the table – like street, postal_code and city etc.

There are many more options – please take a look at the behavior documentation in the class itself or the test cases for details.
One important configuration option is min_accuracy:

'min_accuracy' => GeocodeLib::ACC_SUBLOC

means that the geocoding response is only valid if we can find an address as exact as a sub-locality or better. This can help in validation addresses since incorrect addresses would fall back to pretty unspecific results (and therefore bad accuracy).

Advanced tips

If you have a country Model related to your addresses you probably want to include the country in your query (otherwise it might find the address in some other country).
Just passing the country_id will not do the trick, of course. You should manually add the field country to your data before passing it on to the model:

$this->request->data['Address']['country'] = $countryName; // as a string
if ($this->Address->save($this->request->data) {}

My plan was to automatically extract the country name in the behavior if country_id is passed – but that might be a little bit too much magic.

Searching/Filtering

This is a little bit more complicated. Basically, if we want to retrieve results based on distance we need to pass one point (lat/lng) to the behavior and calculate the distance in the database at runtime. Since 2.x it is very easy to use virtual fields for this.
The behavior has support for the virtual fields needed to do this using setDistanceAsVirtualField():

The default unit is GeocodeLib::UNIT_KM but can easily be switched to miles, nautical miles, …

Note: If you do not have lat/lng fields in your table yet, you need to add them first. Then run a loop for all records using save() to geocode the address etc. After this you will be ready to use filtering here. You cannot geocode at runtime. It is too costly. So do it once on save and then you can use the lat/lng fields as often as you want.

Validation

The behavior adds two new rules you can use: validateLatitude and validateLongitude.
See the test cases for details on how to use it.

Todos

I want to cleanup and rewrite some of it – as soon as the test cases are complete.
Not just because this code is mainly from 1.2 and only "upgraded", but also because throwing Exceptions and improving the overall workflow would probably be a good idea.

How can I get shops + the distance. I only get data with the correct distance. How can I achieve this ?

I am using cake3

Best regards.

Mark

August 5, 2015 at 19:25

It should find all records with the distance included as field. Unless you specify the limit as additional condition. The case test proofs that AFAIK.

Jure

September 1, 2015 at 11:42

Hi Mark,

it is me again. I checked the TestCase, but I still got the problem. I didn’t get it.
If I set the distance condition to the option, I get an error – Unknown column ‘distance’ in ‘where clause’

It looks like I missed something in model?

Thank you for your help!

Justin McCarty

August 9, 2016 at 04:50

Hi am using your Geocoder and have had a lot of fun with it. I was playing with it on localhost computer and it geocodes coords on save and then I used your the custom distance finder which to retrieve the data. When I moved my development to my digital ocean server the customer finder quit working. It returns a sql error: Documentation API
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘events.lat’ in ‘where clause’.
I think I’ve read everything in the docs and I can’t figure out what has gone haywire. The code I am running is straight from the docs

Hallo Mark,
Im new to Cakephp and would like to include Google Maps into my application and display markers from addresses stored in my Database. I came across ur Geocoding Tool and would like to use it. But Im already struggling to get it working.
After including the tools plugin I followed the first step, but it is causing an error:
Error: Call to undefined method Cake\Core\App::uses()

So obviously something is missing.
Also I opened the GoogleMapsHelper from 2010. But Im not sure where to include the $config file.
It would be great if u could point me into the right direction.

Mark

June 8, 2017 at 22:05

App::uses() is 2.x – which is when this post was written.
You need to be using use statements now in 3.x.