This is a helper to generate GoogleMap maps (dynamic and static ones) in your CakePHP views.
Note: Google Maps API V2 is marked “deprecated”. API V3 is supposed to be faster and more compatible to mobile browsers. Details Also new: A googlemaps key is not necessary anymore.
Usage
I wanted to keep it as simple as possible (otherwise you could use the maps with plain js right away).
You may set up configs/defaults in your config file:
$config['Google'] = array( 'zoom' => 6, 'lat' => 51.1, 'lng' => 11.2, 'type' => 'H', // Roadmap, Satellite, Hybrid, Terrain 'size' => array('width'=>'100%', 'height'=>400), 'staticSize' => '500x450', );
Please include the Tools Plugin in your bootstrap with CakePlugin::loadAll() or CakePlugin::load('Tools').
Now you need to add the helper to the controller (or the action):
// globally public $helpers = array(..., 'Tools.GoogleMapV3'); // OR in the action: public function map() { $this->helpers[] = 'Tools.GoogleMapV3'; // rest of your code }
Since there are many possible ways to include the required javascript file I formed an own method for it:
<?php // include jQuery >= 1.4 echo $this->Html->script('jquery'); // or wherever it is in your js folder // include the Google js code echo $this->Html->script($this->GoogleMapV3->apiUrl()); // OR include it manually without cake (or use your own asset stuff) echo '<script type="text/javascript" src="'.$this->GoogleMapV3->apiUrl().'"></script>';
You may also let the helper include it automatically – just pass the option “autoScript” => true to the map() method in the next step.
Now we can use it.
Interactive Maps
// init map (prints container) echo $this->GoogleMapV3->map(array('div'=>array('height'=>'400', 'width'=>'100%'))); // add markers $options = array( 'lat' => 48.95145, 'lng' => 11.6981, 'icon'=> 'url_to_icon', // optional 'title' => 'Some title', // optional 'content' => '<b>HTML</b> Content for the Bubble/InfoWindow' // optional ); // tip: use it inside a for loop for multiple markers $this->GoogleMapV3->addMarker($options); // print js echo $this->GoogleMapV3->script();
You can also add windows and (custom) events. See the code and its tests for details on that.
Buffering scripts instead of outputting them directly
With 2.x you can also write the JS to the buffer and output it combined anywhere you want in your layout. Just call
$this->GoogleMapV3->finalize(); // replaces script()
instead of echoing the script() then. The script() call must not be used then. Don’t mix those two methods.
Also make sure you got echo $this->Js->writeBuffer(array('inline' => true)); somewhere in your layout then.
Most developers put CSS in the head and JS at the very bottom (before the closing </body> tag). This way, the layout renders very fast and the JavaScript will render last and does not impede the page loading process.
See the next chapter for details.
Directions (with or without additional text)
If you want to print directions from point A to point B, you can do so with:
echo $this->GoogleMapV3->map(); $from = 'Munich'; // needs to be geocoded at runtime $to = array('lat' => 50.51, 'lng' => 13.40); $this->GoogleMapV3->addDirections($from, $to); $this->GoogleMapV3->finalize();
You can either pass in a string to be automatically geocoded or pass an array with lat/lng coordinates.
Note: Geocoding on demand is possible, but slightly slower and less resourceful. It is recommended to geocode in the backend – using PHP and the Plugin classes listed below – and output the coordinates here directly.
Static Maps
These are just images. Very handy if you don’t need the js overhead.
// markers $markers = array( array('lat'=>48.2, 'lng'=>11.1), array('lat'=>48.1, 'lng'=>11.2, 'color' => 'green', ...) ); // paths $paths = array( array( 'path' => array('Berlin', 'Stuttgart'), 'color' => 'green', ), array( 'path' => array('44.2,11.1', '43.1,12.2', '44.3,11.3', '43.3,12.3'), ), array( 'path' => array(array('lat'=>'48.1','lng'=>'11.1'), array('lat'=>'48.4','lng'=>'11.2')), //'Frankfurt' 'color' => 'red', 'weight' => 10 ) ); // some options and image attributes $options = array( 'size' => '500x400', 'center' => true, 'markers' => $this->GoogleMapV3->staticMarkers($markers), 'paths' => $this->GoogleMapV3->staticPaths($paths), ); $attr = array( 'title'=>'Yeah' ); // now display the map image echo $this->GoogleMapV3->staticMap($options, $attr); // you can even add an url to click on $attr['url'] = $this->GoogleMapV3->mapUrl(array('to'=>'Munich, Germany')); echo $this->GoogleMapV3->staticMap($options, $attr);
As you can see, we can now mix lat/lng and normal addresses (which get automatically geocoded in the background).
Map Links
If you want to redirect to maps.google.com (for directions etc) you can use this method.
// leave "from" empty for the user $url = $this->GoogleMapV3->mapUrl(array('to'=>'Munich, Germany')); echo $this->Html->link('Visit Me', $url, array('target'=>'_blank') // coming from a posted form or whatever $url = $this->GoogleMapV3->mapUrl(array('to'=>'Munich, Germany', 'from'=>$from)); echo $this->Html->link('Directions to me', $url, array('target'=>'_blank')
Last but not least
Other updates: - multiple paths and markers - visible scope - custom icons possible
For more examples check out the test case. It contains several more sophisticated examples.
Helper Code
The code can be found in my github rep: cakephp-google-map-v3-helper
Update 2012-02-01
All urls/links are now HTTPS sensitive. So if you display the map on a secure site (https://...) it will also use the same connection for all the google stuff (images, js, …). This is necessary for HTTPS to be valid.
Update 2012-09-09: GoogleMapsV3Helper v1.3 – not backwards compatible
The helper is now E_STRICT compliant. The methods url() and link() are now mapUrl() and mapLink().
Update 2013-02-25 ms
directions() has been added to print directions from point A to B. Also basic geocoding capabilities have been added for this method as well as addMarker().

Mark
March 23, 2012 at 11:44
Is it possible that you got an old version of it?
The line you are talking about is `961` in my file.
Chris W
August 29, 2012 at 16:21
Is this currentley working with CakePHP 2.x ??
I've tried it, geting 'Map cannot be displayed!'
Mark
August 29, 2012 at 18:41
yes, all 2.x
then you didnt include your JS files correctly.
user proper debugging tools like firefox+firebug to display those js errors and correct your mistakes. then it should run flawlessly.
fco
August 31, 2012 at 08:55
Hi Mark, Thanks for this very useful piece of code.
I'm using your helper with cake 2.2.1, it's working ok, but I keep getting this error:
Strict (2048): Declaration of GoogleMapV3Helper::url() should be compatible with Helper::url($url = NULL, $full = false) [APP/View/Helper/GoogleMapV3Helper.php, line 28]
Any idea what may be causing it?
Thanks for your help!
Mark
August 31, 2012 at 11:36
yes, its the E_STRICT default from PHP5.4
its minor and absolutely not critical – but still annoying (see http://www.dereuromark.de/2012/03/06/e_strict-compliance-in-cake/).
I use in my core.php
'level' => E_ALL & ~E_STRICT
to not throw the strict warnings for now.
fco
September 3, 2012 at 09:20
Thanks Mark,
It did the worked for me
sebastien
September 13, 2012 at 14:40
hello ! thank for your work
but i don't understand how i can do for a draggable marker ( and automatic position in a input form )
thank for help
sebasien
charbel
October 23, 2012 at 06:02
can u place and example for marker clustering please??
Giorgio
November 7, 2012 at 22:27
It would be interesting, that i can place a link extern to the map, that can open a infoWindow of a assigned marker. Is it possible?
Mark
November 8, 2012 at 00:48
of couse its possible. you just need some custom js to trigger the event
Yien Bin
December 6, 2012 at 13:15
Hello Mark,
Nice work, is the "Draggable" marker option ready in the helper? I can't seem to find it.
Carlos
December 8, 2012 at 05:51
how can i put the a marker in my current location?, or the nearest to.
Marius
December 10, 2012 at 10:42
Hi Mark,
thanks for this great helper
I got i little problem regarding the markers.
The map works fine, but i dont see any marker i added.
Any experience with this kind of bug?
Mark
December 10, 2012 at 10:45
@carlos:
use cutom js to get this information via browser (if allowed) or geocode ip etc in the backend via php
@marius:
Without any code I cannot tell
But they work fine for most of us anyway.
Marius
December 10, 2012 at 11:09
I included the jquery:
and the Maps Aip-Url:
Heres the code from my view:
This is the debug result:
\app\View\Cities\search.ctp (line 93)
(int) 0
Thanks for your fast reply
Marius
December 10, 2012 at 11:11
Sorry, includes look like this:
Html->script('jquery.js'); ?>
Html->script($this->GoogleMapV3->apiUrl()); ?>
Mark
December 10, 2012 at 11:17
use firebug/firefox to debug your js
why are you including the scripts twice? autoScript should already do that.
Marius
December 10, 2012 at 11:34
I forgot to remove the auotinclude. I used it for a test. But also didnt work.
This is the created js, so he got the marker…
I really dont understand that.
Marius
December 10, 2012 at 12:58
Finally got the solution when i found this post on SO:
http://stackoverflow.com/questions/8795104/google-map-v3-cakephp-helper-and-multiple-markers
Eveything is working fine now, maybe you can add this note as comment to your options array for the marker.
note: only set the 'icon' key in the array if you want to use a custom image. Otherwise, they will not show up.
Thanks for this great plugins
Chirayu
February 7, 2013 at 12:12
"careful: with only one marker this can result in too high zoom values!"
I found this statement in the source code with one marker.
I use one marker and my zoom level is showing 21 and not over ridden by anything.
Mark
February 7, 2013 at 12:16
You need to leave autoCenter disabled (should be the default) or disable it again by using 'autoCenter' => false in your initial options for the map. Also make sure you pass a manual zoom level in at some point to avoid google to auto-zoom here.
Kent
February 21, 2013 at 05:13
I received the cakePHP error message:
"Notice (8): Undefined index: inline [APP/Plugin/Tools/View/Helper/GoogleMapV3Helper.php, line 378]"
I added:
to the options array and the error message went away. My this indicate why I am receiving "Map cannot be displayed!" message? No javascript errors in the console. my whole view file looks like:
Mark
February 21, 2013 at 12:03
Thx, it didnt use the right array here. Fixed now
Marcus Radisch
February 24, 2013 at 19:31
Hello Mark,
thanks für your Helper.
How can i change the zoomlevel? Over the cakephp\app\Config\core.php
$config['Google'] = array() i can't change it
Thanks for your help.
Mark
February 24, 2013 at 19:39
That is explained above. You can directly pass it into the map() method.
If you plan on using the configs, please dont put it into core.php but the configs file…
Marcus Radisch
February 26, 2013 at 23:09
Hello mark,
i've a Problem. The map will not be sized to my need.
$googleMapOptions = array(
'autoScript' => true,
'inline' => true,
'id' => $atla['Atla']['id'],
'width' => '200px',
'height' => '200px',
'defaultZoom' => 9,
'lat' => 48.775556, # Stuttgart
'lng' => 9.182778, # Stuttgart
'scrollwheel' => true,
'type' => 'ROADMAP',
'localize' => true,
'geolocate' => true,
'sensor' => true,
The maps is over the whole screen and 400px height.
echo $this->GoogleMapV3->map($googleMapOptions);
Where is my fault?
Mark
February 26, 2013 at 23:24
Did you try to use
You cannot just pass those directly. Take a look at the helper code for clarification (tip: "$_defaultOptions").
Marcus Radisch
February 26, 2013 at 23:39
This runs now, but how i can load the rest of the options out of the array.
The way to add the array in the map doesn't run.
Marcus
Marcus Radisch
March 1, 2013 at 20:28
how can i add html syntax in the contentfield?
Mark
March 1, 2013 at 20:32
Did you take a look at the example above?
Marcus Radisch
March 1, 2013 at 20:36
Yes,
if i use this
i get the
syntax error, unexpected 'Atla' (T_STRING), expecting ')'
error
Mark
March 1, 2013 at 20:38
Because that is invalid PHP. Use an IDE with live syntax correction check.
Marcus Radisch
March 1, 2013 at 20:53
Thanks i found the bug with out the ide
Marcus Radisch
March 2, 2013 at 00:50
Hello Mark,
why get i the list of ids from my foreach from addMarker.
Under my my i can see 0123456789…..
But why?
Marcus
Marcus Radisch
March 3, 2013 at 15:23
Hello Mark,
we use your map Helper in cakePHP an set 20 Markers with addMarker.
Where are the Numbers from. Thats the ID of our DB-Entries
Here an example: http://r5hs.com/backups/array.png
Marcus Radisch
March 3, 2013 at 22:11
We solved it, we use an echo where the echo isn't good
Leendert
April 15, 2013 at 12:56
Hello Mark,
Verry nice plugin!
i have only one problem: is there something to echo the distance in KM when using : $this->GoogleMapV3->addDirections($from, $to); ?
It show A and B correctly but i need to echo the distance.
Thx
Mark
April 15, 2013 at 13:00
I don't know. Use the normal way of geocoding it in the backend (PHP) and work with the coordinates in your view then. That will be no issue then.
PJH
April 22, 2013 at 22:02
Shouldn't the shadow URL be urlencoded in the same manner that the icon URL is? i.e. from
to
PJH
April 22, 2013 at 22:10
.. in fact – that's not the problem I have…
PHP code:
Resultant CSS:
Something I'm doing wrong?
Mark
April 23, 2013 at 01:55
There was indeed a small bug regarding url strings here.
It is fixed in the current master branch.
Thank you for pointing it out.
Eduardo
May 22, 2013 at 19:17
Hi Mark, thanks for your great work, it helped me a lot, i have now a problem, when i try to display the map in a modal box it displays: Map cannot be display, i was trying to fix that but i can't figure out a solution, i don't know if there is a workaround.
Chirayu
May 31, 2013 at 13:14
my map does not load with correct size, but when I resize my browser, then it loads in the correct size. here is what I have written, it is enough I guess…